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