Nodejs知识总结(二)

一、同步、异步

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("可写流关闭");
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值