如果文件存在,带有 'wx' 标志的 fs.writeFile 不会失败

tso*_*orn 5 fs node.js

我正在使用FileCookieStore它需要一个 cookiefile 的路径,并且该文件已经创建。我想使用fs.writeFile,如果它不存在创建此文件,但如果它来覆盖它确实存在。但是,在下面的实现中,即使 cookiefile 存在,它也会覆盖 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
}
Run Code Online (Sandbox Code Playgroud)

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

kri*_*nik 0

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

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