【问题标题】:Update a file only if it exists Node仅当文件存在时才更新文件节点
【发布时间】:2016-09-05 00:09:30
【问题描述】:

我只想在文件存在的情况下使用 NodeJs 更新文件。 怎么做。 我阅读了节点文档并且不推荐使用 fs.exists 。 如果我直接使用 fs.writeFile 它将创建一个新文件,如果一个不存在。

如何仅在文件存在时更新文件。 谢谢。

【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    试试这个:

    var fs = require('fs');
    var myFile = './mono.txt';
    
    try {
      if (!fs.accessSync(myFile)) console.log('File does already exist');
    }
    catch (exc) {
      fs.writeFile(myFile);
    }
    

    【讨论】:

    • fs.existsSync(path) 已弃用。
    • 试试fs.accessSync(...)
    • 请不要同步 IO。
    【解决方案2】:

    使用 fs.open 和 fs.write。

    你需要的fs.open标志:

      * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.
    

    【讨论】:

    • 这也是我的答案 =D
    • 您也可以使用fs.writeFile() 做到这一点。这是正确的答案。
    • 在 fs.writeFile 中使用了 'r+' 标志。谢谢
    • @MadaraUchiha 在使用 r+ 编写 fs.writeFile 时,它​​不会覆盖文件。它只是替换字符。如何覆盖文件?
    【解决方案3】:

    来自NodeJs 4.x documentation

    var fs = require('fs');
    
    fs.access('/path/to/your/file', fs.F_OK, (err) => {
       if (!err) {
         // File exists, update your file
       }
    });
    

    fs.F_OK - 文件对调用进程可见。这对于确定文件是否存在很有用,但没有说明 rwx 权限。未指定模式时默认。

    您也可以使用标志fs.R_OK | fs.W_OK | fs.X_OK额外检查调用进程的rwx权限。

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 2016-09-11
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      相关资源
      最近更新 更多