一.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()