node.js的fs,http,path模块的使用

内置模块fs的使用

  • 内置模块的基本使用
//01引入,导包
const fs = require('fs');
//调用unlink方法删除方法
//第一个参数。删除的文件路径
//第二个参数,回调函数
fs.unlink('./tmp/hello.txt', (err) => {
    if (err) throw err;
    console.log('已成功地删除文件');
});
  • 读文件
//导包
const fs = require('fs')
//使用readfile方法读取文件
//第一个参数:文件的路径
//第二个参数:可选参数,读取文件的编码格式
//第三个参数,回调函数
fs.readFile('etc/1.txt', 'utf-8', (err, data) => {
    if (err) throw err;
    //err是一个错误对象,如果没有错误就返回一个null
    console.log(data);
    /**
     * PS C:\Users\Administrator\Desktop\jq\0705\内置模块fs的使用> node 02读文件.js
        dadadadadaada
     */
});
  • 写文件
//导包
const fs = require('fs')
//02调用writefile方法  没有文件会新建一个
//第一个参数 写入文件的路径
//第二个参数 要写入的内容
//第三个参数 回调函数
const data = `
望庐山瀑布
唐.李白
日照香炉生紫烟,
遥看瀑布挂前川,
飞流直下三千尺,
疑是银河落九天.|

`;
fs.writeFile('etc/文件.txt', data, (err) => {
    if (err == null) {
        console.log('文件已被保存');
    }

});

内置模块http的使用

  • 使用http模块创建一个服务器
//使用http模块创建一个服务器

//1.导入模块
const http = require('http');
//2.创建一个服务器
const server = http.createServer((request, response) => {
    //3.设置返回给用户看的内容
    // response.end("hello world")
    //如果要想返回的中文不乱码,就要设置响应头
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.end("初次见面")
})


//4.开启服务器
//端口
server.listen(8087, () => {
    console.log("服务器开启了:8087")
})

内置模块path的使用

  • 和路径有关的两个变量
//__dirname   当前文件所在文件夹的绝对路径
//__filename 当前文件的绝对路径
console.log(__dirname)
//c: \Users\Administrator\Desktop\jq\0705\内置模块path的使用
console.log(__filename)
//c:\Users\Administrator\Desktop\jq\0705\内置模块path的使用\03和路径有关的两个变量.js

//自己拼接 要读取文件的 绝对路径
//也是绝对路径,但是没有写死,通过获取当前文件所在的文件夹的路径拼接而成
console.log(__dirname + "\\etc\\1.txt")
//c:\Users\Administrator\Desktop\jq\0705\内置模块path的使用\etc\1.txt

  • 内置模块path的基本使用

//下面使用__dirname来拼接一个绝对路径
//有点的时候会少写一个斜杠
// const fullPath = __dirname + "\\etc\\1.txt";

//为了避免出现少写斜杠的错误,使用path拼接

//导包
const path = require('path');
//使用方法
//join方法是把路径片段。连接成一个新的路径
const fullPath = path.join(__dirname, 'etc', '1.txt')
// console.log(fullPath)/c:\Users\Administrator\Desktop\jq\0705\内置模块path的使用\etc\1.txt

-使用path模块拼接的路径读取文件

//1.导入模块
const path = require('path');
const fs = require('fs');
//调用方法
//2.1使用path.join拼接一个绝对路径
const fullPath = path.join(__dirname, 'etc', '1.txt')
fs.readFile(fullPath, 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data)
    } else {
        console.log(err)
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值