【问题标题】:How to ensure all directories exist before to fs.writeFile using node.js如何使用node.js确保所有目录都存在于fs.writeFile之前
【发布时间】:2016-02-10 02:11:07
【问题描述】:

我想知道在写入新文件之前确保路径中的所有文件夹都存在的正确方法是什么。

在以下示例中,代码失败,因为文件夹 cache 不存在。

    fs.writeFile(__config.path.base + '.tmp/cache/shared.cache', new Date().getTime(), function(err) {
        if (err){
            consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line, 'error');
        }else{
            consoleDev('Cache process done!');
        }

        callback ? callback() : '';
    });

解决方案:

    // Ensure the path exists with mkdirp, if it doesn't, create all missing folders.
    mkdirp(path.resolve(__config.path.base, path.dirname(__config.cache.lastCacheTimestampFile)), function(err){
        if (err){
            consoleDev('Unable to create the directories "' + __config.path.base + '" in' + __filename + ' at ' + __line + '\n' + err.message, 'error');
        }else{
            fs.writeFile(__config.path.base + filename, new Date().getTime(), function(err) {
                if (err){
                    consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line + '\n' + err.message, 'error');
                }else{
                    consoleDev('Cache process done!');
                }

                callback ? callback() : '';
            });
        }
    });

谢谢!

【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    使用mkdirp

    如果你真的想自己做(递归):

    var pathToFile = 'the/file/sits/in/this/dir/myfile.txt';
    
    pathToFile.split('/').slice(0,-1).reduce(function(prev, curr, i) {
      if(fs.existsSync(prev) === false) { 
        fs.mkdirSync(prev); 
      }
      return prev + '/' + curr;
    });
    

    您需要切片来省略文件本身。

    【讨论】:

    • 你应该删除切片。它会跳过最后一个文件夹,因为您正在处理上一个值。即使没有 slice,它也永远不会到达文件,因为它是最后一个 current,并且永远不会是 prev。
    【解决方案2】:

    fs-extra 有一个我发现对执行此操作很有用的函数。

    代码类似于:

    var fs = require('fs-extra');
    
    fs.ensureFile(path, function(err) {
      if (!err) {
        fs.writeFile(path, ...);
      }
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用 fs.existsSync 来检查您的目录是否存在,如果不存在则创建它:

      if (fs.existsSync(pathToFolder)===false) {
          fs.mkdirSync(pathToFolder,0777);
      }
      

      【讨论】:

      • 这会创建所有不存在的路径级别吗?另外,为什么要在异步操作中引入同步代码?
      • 同步会阻止您的 writefile 在文件夹创建之前运行。 @hobbs mkdirp 是个不错的选择。
      • 感谢您的回答,同步或异步确实不是问题。如果它确实有效,我会尽快尝试并接受答案;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2013-04-14
      • 2023-04-02
      相关资源
      最近更新 更多