fs.异步读取
fs.readFile('文件路径'[,选项], function (err, data) {
if (err) {
console.log('有错误,错误内容是', errr)
} else {
console.log('读入文件正确,内容是', data)
}
});
fs.同步读取
const fs = require("fs")
let rs = fs.readFileSync('文件路径',"utf8");
console.log(rs)
try {
const fs = require("fs")
let rs = fs.readFileSync('文件路径',"utf8");
console.log(rs)
} catch(err) {
console.log(err)
}
fs.同步写入
var fs = require("fs");
var fd = fs.openSync("hello.txt", "w");
fs.writeSync(fd, "今天天气真好");
fs.closeSync(fd);
fs.异步写入
var fs = require("fs");
fs.writeFile("hello.txt", "这是通过writeFile写入的内容", { flag: "w" }, function (err) {
if (!err) {
console.log("写入成功");
}
});