node引入及使用
1、引入fs模块
let fs = require('fs');
2、读取文件
fs.readFile('参数一:文件路径名',参数二:回调函数(错误信息,数据(buffer类型))
{
})
示例:
fs.readFile('./node.txt', function (error, data) { //读取node.txt文件 if (error) { console.log(error); //如果错误打印error错误信息 } else { console.log(data.toString()); //如果成功打印data数据,数据类型改为string类型 } })
3、操作(修改)文件
fs.readFile('参数一:文件路径名',参数二:‘修改的内容’,参数三:回调函数(错误信息,数据(buffer类型))
{
})
示例:
fs.writeFile('./node.txt','hello111111111',function (error,data) { //修改node.txt中内容为hello11111111 if(error){ console.log(error); //如果失败打印错误信息 }else{ fs.readFile('./node.txt', function (error, data) { //如果成功执行读取操作 if (error) { console.log(error); } else { console.log(data.toString()); } }) } })
4、读取文件夹
fs.readdir('参数一:文件路径名',参数二:回调函数(错误信息,数据(结果为数组))
{
})
示例:
fs.readdir('../day01',function (error,data) { if(error){ console.log(error); }else{ console.log(data); } })
5、创建文件夹fs.mkdir('地址文件名',function (error, data) {})
fs.mkdir('../dir_4',function (error, data) { if (error) { console.log(error); } else { console.log(data); fs.readdir('../day01', function (error, data) { if (error) { console.log(error); } else { console.log(data); } }) } })
执行结果:
![](https://img2020.cnblogs.com/blog/2506251/202108/2506251-20210823115604489-1992050430.png)
6、运行程序
node 文件名
D:\新桌面\前端\node\day01> node .\node_1.js 执行node_js程序