前言
fs是filesystem的缩写,该模块提供本地文件的读写能力,基本上是POSIX文件操作命令的简单包装。但是,这个模块几乎对所有操作提供异步和同步两种操作方式,供开发者选择。
一、文件读取
文件读取又分为同步读取(readFileSync())和异步读取(readFile())
//1、文件同步读取
const bufferStr = fs.readFileSync('./file/test.txt'}); console.log(bufferStr);
// 因为没有声明encoding 所以返回的是二进制数据
//<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 21> const str = fs.readFileSync('./file/test.txt',{
encoding:'utf-8'
}); console.log(str);
//Hello world!
//错误处理
try{
var errStr = fs.readFileSync('test.txt');
}catch(err){
console.log(errStr);
} //因为文件不存在,所以 打印出 undefined //2、文件异步读取
fs.readFile('./file/test.txt',{encoding:'utf-8'}, (err,data) =>{
if(err) throw err;
console.log('2.1读取数据成功,数据内容为:'+ data);
});
二、文件写入
文件写入包括:fs.writeFile(异步)、fs.writeFileSync(同步)
格式:fs.writeFile(filename, data, [options], callback)
[options]
@param {Object} [options]
@param {String} options.encoding 编码,默认是utf8
@param {Number} options.mode=438 模式
@param {String} options.flag=w 写文件的模式
@param {Function} callback 回调方法
const fileName = 'wirteFile_01.txt'; fs.writeFile(fileName, 'Hello World !', (err) => {
if(err) throw err;
console.log(fileName + '不存在,被创建了!');
}); //往存在的文件内写内容
fs.writeFile(fileName, 'no pain no gain', (err) => {
if(err) throw err;
console.log(fileName + '文件被修改了!');
}); //往文件内追加内容
fs.writeFile(fileName, 'stay hungry stay foolish',{flag : 'a'}, (err) => {
if(err) throw err;
console.log(fileName + '文件被修改了,内容追加!');
});
fs.writeFileSync(同步)
与异步差不多,就是没有回调。
三.文件删除
//异步
fs.unlink('./file/test.txt', (err) => {
if (err) throw err;
console.log('成功删除file中的test.txt');
}); //同步
fs.unlinkSync('./file/test.txt', (err) => {
if (err) throw err;
console.log('成功删除file中的test.txt');
});
四、文件的监听事件
//文件的事件监听
fs.watch('./file', {encoding:'utf-8'}, (eventType, filename) =>{
if(filename){
console.log('文件名:' + filename + '事件类型:' + eventType);
}
}); //文件名:test3.txt事件类型:rename
//文件名:hhh.txt事件类型:rename
//文件名:hhh.txt事件类型:change
参考:官方文档