【问题标题】:fs.writeFile with 'wx' flag does not fail if file exists如果文件存在,带有 'wx' 标志的 fs.writeFile 不会失败
【发布时间】:2016-02-05 03:51:09
【问题描述】:

我正在使用FileCookieStore,它需要一个 cookie 文件的路径并且该文件已经创建。如果该文件尚不存在,我想使用fs.writeFile 创建此文件,但如果它确实 存在,则不要覆盖它。然而,在下面的实现中,即使它存在,它也会覆盖 cookiefile 的内容,即使 wx -flag 应该抛出一个错误并且不会覆盖已经存在的文件。

var cookiePath = "cookie.json"

fs.writeFile(cookiePath, null, { flags: 'wx' }, function (err) {
    if (err) throw err;
});

var j = request.jar(new FileCookieStore(cookiePath));
request = request.defaults({ jar : j });

function login(callback) {
    // puts data into j which automatically writes the content to cookiePath
}

我是否误解了writeFilewx 标志的正确用法?如果我运行login(),cookie 的内容会自动保存到 cookie.json,但如果我再次运行该文件而不调用loginfs.writeFile 会清空 cookiefile。

【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    你的代码应该是:

    fs.writeFile(cookiePath, null, { flag: 'wx' }, 函数 (err)

    :)

    【讨论】:

    • 确实只是flag
    【解决方案2】:

    根据文档,writeFile 方法的语法是fs.writeFile(file, data[, options], callback)

    我可以看到您正在发送 null 来代替要写入的数据。这可能是您的空 cookie 文件背后的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多