核心模块:Node.js中自带的一些模块
node中的核心模块 包括fs、path、http、url
fs文件系统模块
fs模块是用来操作文件的模块。它提供了一系列的方法和属性,用来满足用户对文件的操作。
使用fs模块时,先引入。
//引入核心模块fs
const fs = require("fs");
打印fs的内容时,使用utf8,或者toString(),将二进制数据流转换为 汉字等。
文件操作
1. 读文件 fs.readFile()
// 异步操作
fs.readFile("day1/ok.txt", (err, data) =>{
if(err){
console.log("文件读取失败,原因是" + err);
return;
}
console.log(data.toString());
})
console.log("peace");
// 同步操作
const data = fs.readFileSync("day1/ok.txt", "utf8");
console.log(data);
console.log("peace");
<