一.fs-extra 文件管理node
$npm install fs-extra --save
1.建立一個目錄npm
fs.mkdir(path, [mode], [callback(err)]) path 將建立的目錄路徑 mode 目錄權限(讀寫權限),默認0777 callback 回調,傳遞異常參數err
建立目錄ui
await fs.mkdir(path.join(__dirname, "/images", dir));
2.刪除一個空目錄url
fs.rmdir(path,callback)
3.讀取一個目錄blog
fs.readdir(path,callback(err,files))
四、複製文件圖片
fs.copy('G:/works/node爬蟲/images', 'G:/works/node爬蟲/test', function(err) { if (err) return console.error(err) console.log("success!") });
5.移動文件、目錄, 會刪除之前的, 等於更名ip
fs.move('G:/works/node爬蟲/images', 'G:/works/node爬蟲/testss', function(err) { if (err) return console.error(err) console.log("success!") });
6.刪除文件、目錄rem
fs.remove('G:/works/node爬蟲/images2', function(err) { if (err) return console.error(err) console.log("success!") })
7.建立文件、目錄get
// 目錄 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"是斷行it
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()