node之fs模块
fs模块
为什么用fs模块
为了读取文件和写入文件
const http = require("http");
const fs = require("fs");// fs文件系统模块 file system
let server = http.createServer(function (req, res) {
/*fs.readFile(path,callback)*/
//默认读取文件,是按照二进制读取的
fs.readFile("./1.txt", function (err, data) {
if (err) {
console.log("error", err);
} else {
res.write(data);
res.end();
}
});
//传入编码,会自动把读取的二进制转码成字符串
fs.readFile("./1.txt", "utf-8", function (err, data) {
if (err) {
console.log("error", err);
} else {
res.write(data);
res.end();
}
});
//fs.writeFile(path,data,callback)
fs.writeFile("./1.txt", "123", function (err) {
if (err) {
console.log("error", err);
} else {
console.log("success");
}
});
});
// 监听
server.listen(8000);
浙公网安备 33010602011771号