File System | 异步文件的写入

  1. 打开文件
    • fs.open(path, flags[, mode], callback)
      • 用来打开一个文件
      • callback 回调函数
      • 异步调用的方法,结果都是通过回调函数参数(arguments)返回
      • 回调函数两个参数
        • err 错误对象,如果没有错误则为 null
        • fd 文件描述符
  2. 写入文件
    • fs.write(fd, string[, position[, encoding]], callback)
  3. 关闭文件
    • fs.close(fd, 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);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。