一、同步、异步
1、所有的方法都有异步和同步的形式;
2、node里关于文档的操作方法基本都给了2份,即同步和异步;
3、使用前导入核心模块
const fs = require("fs");
4、重命名异步
fs.rename("ok.txt","yes.txt",function(err){
if (err) throw err;
console.log("重命名成功");
})
5、重命名同步
fs.renameSync("ok.txt","yes.txt");
二、fs 文件操作
1、读文件 fs.readFile()
fs.readFile("./yes.txt",function (err, data) {
if(err) throw err;
console.log(data);
//data是一个buffer
})
fs.readFile("./yes.txt","utf8",function(err,data) {
if(err) throw err;
console.log(data);
//以指定编码输出
})
2、写文件 fs.writeFile()
fs.writeFile("./yes.txt","今天又来敲代码啦~",function(err) {
if (err) throw err;
})
●默认就是utf8的编码格式;
●效果:删掉文档原内容,写入新内容,如果指定文档不存在 ,则新建;
3、追加 fs.appendFile()
for (let i=0; i<10; i++) {
fs.appendFile("./yes.txt","item" + i + "\n",function(err){
if(err) throw err;
})
}
4、拷贝 fs.copyFile()
fs.copyFile("./yes.txt","./ok.txt",function(err) {
if(err) throw err;
})
三、fs 流操作(一般读取的是大文件)
1、读取流
const fs = require("fs");
var rs = fs.createReadStream("./ok.txt",{encoding:"utf8"});
rs.on("open", function() {
cosole.log("可读取开启");
})
rs.on("data",function(chunk) {
cosole.log(chunk);
})
rs.on("end",function() {
console.log("可读流读取结束");
})
rs.on("close",function() {
console.log("可读流关闭");
})
2、写入流
const fs = require("fs");
var ws = fs.createWriteStream("./ok.txt");
ws.write("听说明明很美!");
ws.end();
ws.on("open",function() {
cosnole.log("可写流开启");
})
ws.on("close",function() {
console.log("可写流关闭");
})