Node-核心模块

一、同步&异步

所有的方法都有同步和异步的形式

node里关于文档的操作方法基本都给了2份,即同步与异步

使用前需要导入核心模块(核心模块:下载node.js时自带的)

二、fs——文件操作

1、读文件  fs.readFile()  异步操作

    fs.readFile("所要读的文件","utf8"function(err,data){
    if(err) throw err;
    console.log(data);    
})

    fs.readFileSync()  同步操作
    const data = fs.readFileSync("所要读的文件","utf8")
    console.log(data)

2、写文件   fs.writeFile()  

    fs.writeFile("要写入的文件","写入的内容",function(err){
    if(err) throw err;
})

    效果:会删掉文档原来的内容,写入新的内容,如果指定的文档不存在,则新建

    其中新建的文档必须为同级
3、追加  fs.appendFile()
    
    fs.appendFile("./yes.txt","./no.txt",function(err){
    if(err) throw err;
})    yes的后面追加no的内容
    

4、拷贝 fs.copyFile()

    fs.copyFile("./yes.txt","./no.txt",function(err){
    if(err) throw err;
})    yes的内容copy到no

三、fs——流操作
 

一般读取的时大文件

1、读取流

    const fs = require("fs");  //引入核心模块
    const rs = fs.createReadStream("读取的文档",{encoding:"utf8"});
    rs.on("open",function(){
        console,log("可读流开启");
})           

    rs.on("data",(chunk) => {
        console.log(chunk);  //chunk时一个Buffer,当前读取的数据片段,二进制数据流
})

    rs.on("end",() => {
        console,log("可读流读取结束");
})

    rs.on("close",() => {
        console,log("可读流guanbi");
})


2、写入流

    const fs = require("fs");  //引入核心模块
    const ws = fs.createWriteStream("写入的文档");
    ws.write("写入的内容");
    ws.end();
    ws.on("open",function(){
        console,log("可写流开启");
})
    ws.on("close",function(){
        console,log("可写流关闭");
})

四、path

basename()        文件名+后缀

dirname()        路径名

extname()        后缀名

join()        拼接路径

parse()        将路径解析成对象

format()        将对象整合成路径字符串

isAbsolute()        是否是一个绝对路径

 五、http

完整的URL路径:协议+IP/域名+端口号+路由+?+参数信息

第一个http服务

var http = require("http");   //引入核心模块

http.creatServer((req,res) => {
    res.writeHead(200,{"content-type":"text/html;charset=utf-8"}); //一定要写响应头
    res.end(); //向前端返回内容
}).listen(port); //监听端口并开启服务

 六、url

const {URL} = require("url")    //引入核心模块

const url = new URL("http://localhost:8080/index.html?a=1&b=2")  //必须是完整的url

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值