How to ensure all directories exist before fs.writeFile using node.js

I am wondering how to correctly find the entire folder in the path before writing a new file.

In the following example, the code fails because the folder cache

does not exist.

    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() : '';
    });

      

Decision:

    // 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() : '';
            });
        }
    });

      

Thank!

+3


source to share


3 answers


Use mkdirp .

If you really want to do it yourself (recursively):



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;
});

      

You need the snippet to omit the file itself.

+3


source


You can use fs.existsSync to check if your directory exists and create it if not:



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

      

+2


source


fs-extra has a function that I found useful for this.

The code will look something like this:

var fs = require('fs-extra');

fs.ensureFile(path, function(err) {
  if (!err) {
    fs.writeFile(path, ...);
  }
});

      

+2


source







All Articles