nodejs文件操作
1.读文件
1.异步读取文件全部内容
fs.readFile(path[, options], callback)
let data= fs.readFile(video.id,function(err,data){ if(err){ console.log(err); } console.log(data); })
2.同步读取文件全部内容
fs.readFileSync(path[, options])
data = fs.readFileSync(video.id)
2.读取目录内容
1.异步
fs.readdir(path[, options], callback)
let fList = fs.readdirSync(that.fileLoc,function(err,files){ if(err){ console.log(err); } console.log(files); })
2.同步
fs.readdirSync(path[, options])
let fList = fs.readdirSync(that.fileLoc)
console.log(fList)
2.写文件
1.异步
fs.writeFile(file, data[, options], callback)
当 file 是文件名时,则异步地写入数据到文件(如果文件已存在,则覆盖文件)。 data 可以是字符串或 buffer。
//ssPath:文件目录,例如:E:\hb\demo\demohtml.txt
//buf:文件流,
//quan:权限
let quan = {
mode: "0777"
}
fs.writeFile(ssPath, buf, quan,function(err){
if(err) throw err;
})
2.同步
fs.writeFileSync(file, data[, options])
fs.writeFile(ssPath, buf, quan)
3.判断文件是否存在
1.异步
fs.exists() 已弃用
2.同步
fs.existsSync(path)
if (fs.existsSync('文件')) { console.log('该路径已存在'); }
4.文件大小
1.异步
fs.statSync(path[, options])
let stats = fs.stat(video.src,function(err,stats){ if(err){console.log(err) } console.log(stats)})
2.同步
fs.stat(path[, options], callback)
let stats = fs.statSync(video.src)
console.log(stats)
//文件大小
console.log(stats.size)
[官方建议]:不建议在调用 fs.open()、 fs.readFile() 或 fs.writeFile() 之前使用 fs.stat() 检查文件的存在性。 而是应该直接地打开、读取或写入文件,如果文件不可用,则处理引发的错误。
若要只检查文件是否存在,但没有更多的操作,则建议使用 fs.access()。
5.删除文件
1.异步
fs.unlink(path, callback)
fs.unlink('文件.txt', (err) => { if (err) throw err; console.log('文件已被删除'); });
2.同步
fs.unlinkSync(path)
fs.unlinkSync('文件.txt')
6.创建目录
1.异步
fs.mkdir(path[, options], callback)
// 创建 "/目录1/目录2/目录3",不管 "/目录1 和 /目录1/目录2" 是否存在。
fs.mkdir('/目录1/目录2/目录3', { recursive: true }, (err) => { if (err) throw err; });
当 path 是已存在的目录时,调用 fs.mkdir() 仅在 recursive 为 false 时才会导致错误。2.同步
fs.mkdirSync(path[, options])
fs.mkdirSync(_path);
7.删除目录
1.异步
fs.rmdir(path[, options], callback)
2.同步
fs.rmdirSync(path[, options])
fs.rmdirSync(that.sPath)