文件I/O是由简单封装的标准POSIX函数提供。通过require('fs') 使用该模块。所有的方法都有异步和同步的形式。
异步方法的最后一个参数都是一个回调函数。传给回调函数的参数取决于具体方法,但回调函数的第一个参数都会保留给异常。如果操作成功完成,则第一个参数回事null或undefined。
const fs = require('fs');
// 编码为utf8
fs.readFile('./readme.txt', 'utf8',(err,data) => {
if (err) throw err;
console.log(data);
});
文件不存在:
/home/dex/web/nodejs/readfile.js:4
if (err) throw err;
^
Error: ENOENT: no such file or directory, open './readme'
文件存在:
This is a readme file
同步操作:
const fs = require('fs');
// 同步操作
const data = fs.readFileSync('./readme.txt', 'utf8');
console.log(data);
This is a readme file
同步比异步先执行,高并发的时候同步可能挡住其他用户的访问,web中推荐使用异步操作,。
如何写文件
const fs = require('fs');
fs.writeFile('./text','Hello World!',{ encoding: 'utf8' },err => {
if(err) throw err;
console.log('Done!');
})
另外可以换成一个Buffer来写:
const fs = require('fs');
const content = Buffer.from('Hello WORLD!');
fs.writeFile('./text', content, err => {
console.log('Done!');
})
~
查看文件的详细信息
const fs = require('fs');
fs.stat('./ext', (err,stats) => {
//if (err) throw err; //线上的话可以通过记日志
if (err) {
console.log('文件不存在')
return;
}
console.log(stats.isFile());
console.log(stats.isDirectory());
console.log(stats)
});
true
false
Stats {
dev: 2051,
mode: 33188,
nlink: 1,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 25168511,
size: 12,
blocks: 8,
atimeMs: 1544415275747.7136,
mtimeMs: 1544415267842.6614,
ctimeMs: 1544415267842.6614,
birthtimeMs: 1544415267842.6614,
atime: 2018-12-10T04:14:35.748Z,
mtime: 2018-12-10T04:14:27.843Z,
ctime: 2018-12-10T04:14:27.843Z,
birthtime: 2018-12-10T04:14:27.843Z }
文件重命名
const fs = require('fs');
fs.rename('./text', 'test.love', err => {
if(err) throw err;
});
文件删除
const fs = require('fs');
fs.unlink('./test.love', err => {});
~
文件夹相关操作
读文件目录:
const fs = require('fs');
fs.readdir('./',(err,files) => {
if (err) throw err;
console.log(files);
});
创建文件夹
const fs = require('fs');
fs.mkdir('test', err => {});
删除文件夹
const fs = require('fs');
fs.rmdir('test', err => {});
监视文件的变化
const fs = require('fs');
fs.watch('./', {
recursive: true
}, (eventType, filename) => {
console.log(eventType,filename);
});
change .readfile.js.swp
rename ttt
*监视可用于本地构建代码
流处理
// 流处理
读
const fs = require('fs');
const rs = fs.createReadStream('readme.txt');
rs.pipe(process.stdout);
This is a readme file
写
/ 流处理
const fs = require('fs');
const ws = fs.createWriteStream('./test');
const tid = setInterval(() => {
const num = parseInt(Math.random()*10);
console.log(num)
if(num<8) {
ws.write(num+'')
}else {
clearInterval(tid);
ws.end() // 结束触发事件
}
}, 200);
ws.on('finish', () => {
console.log('Done!')
});
0
9
Done!
如何解决回调地狱
用promisify:
const fs = require('fs');
const promisify = require('util').promisify;
const read = promisify(fs.readFile);
read('readme.txt').then(data => {
console.log(data.toString());
}).catch( ex => {
console.log(ex);
});
用同步函数解决:
const fs = require('fs');
const promisify = require('util').promisify;
const read = promisify(fs.readFile);
async function test() {
try {
const content = await read('readme.txt');
console.log(content.toString());
} catch(ex) {
console.log(ex);
}
}
test();
没有则显示错误:
{ Error: ENOENT: no such file or directory, open 'readme' errno: -2, code: 'ENOENT', syscall: 'open', path: 'readme' }
看起来像同步,实际上还是异步的写法