- 打开文件
-
fs.open(path, flags[, mode], callback)
- 用来打开一个文件
-
callback
回调函数
- 异步调用的方法,结果都是通过回调函数参数(arguments)返回
- 回调函数两个参数
-
err
错误对象,如果没有错误则为 null
-
fd
文件描述符
- 写入文件
fs.write(fd, string[, position[, encoding]], callback)
- 关闭文件
// 引入 fs 模块
var fs = require("fs");
// 打开文件
fs.open("hello.txt", "w", function (err, fd) {
console.log(arguments);
// 判断是否出错
if (!err) {
console.log(fd);
// 如果没有出错,对文件进行写入操作
fs.write(fd, "aSyncFS writing", function (err) {
if (!err) {
console.log("Success~");
}
// 关闭文件
fs.close(fd, function (err) {
if (!err) {
console.log("Closed!");
}
})
});
} else {
console.log(err);
}
});
// 异步不会有返回值
// console.log(fd);