一.fs-extra 文件管理
$npm install fs-extra --save
1.創建一個目錄
fs.mkdir(path, [mode], [callback(err)]) path 將創建的目錄路徑 mode 目錄權限(讀寫權限),默認0777 callback 回調,傳遞異常參數err
創建目錄
await fs.mkdir(path.join(__dirname, "/images", dir));
2.刪除一個空目錄
fs.rmdir(path,callback)
3.讀取一個目錄
fs.readdir(path,callback(err,files))
4、復制文件
fs.copy('G:/works/node爬蟲/images', 'G:/works/node爬蟲/test', function(err) { if (err) return console.error(err) console.log("success!") });
5.移動文件、目錄, 會刪除以前的, 等於改名
fs.move('G:/works/node爬蟲/images', 'G:/works/node爬蟲/testss', function(err) { if (err) return console.error(err) console.log("success!") });
6.刪除文件、目錄
fs.remove('G:/works/node爬蟲/images2', function(err) { if (err) return console.error(err) console.log("success!") })
7.創建文件、目錄
// 目錄 var dir = 'G:/works/node爬蟲/my' fs.ensureDir(dir, function(err) { console.log(err) // => null //dir has now been created, including the directory it is to be placed in });
// 文件
var file = 'G:/works/node爬蟲/my/file.txt' fs.ensureFile(file, function(err) { console.log(err) // => null //file has now been created, including the directory it is to be placed in });
8.寫入文件, 寫入txt.文件時, "\r\n"是斷行
var file = 'G:/works/node爬蟲/my/file.txt' var str = "hello Alan!" fs.outputFile(file, str, function(err) { console.log(err) // => null fs.readFile(file, 'utf8', function(err, data) { console.log(data) // => hello! }) })
// 下載某圖片到指定目錄
const request = require('superagent') const cheerio = require('cheerio') const fs = require('fs-extra') const path = require('path') function download() { const url2 = "https://imgsa.baidu.com/forum/w%3D580/sign=cbeba091a5014c08193b28ad3a7a025b/1ba6b90e7bec54e7141e3726b5389b504ec26ab4.jpg" const filename = url2.split('/').pop() const req = request.get(url2) req.pipe(fs.createWriteStream(path.join(__dirname, 'images', filename))) } download()