Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

fs

I'm wondering what is the proper way to ensure that all folder in a path exist before to write a new file.

In the following example, the code fails because the folder cache doesn't exists.

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

Solution:

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

Thanks!

like image 601
Vadorequest Avatar asked Sep 14 '25 08:09

Vadorequest


2 Answers

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

The code would be something like:

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

fs.ensureFile(path, function(err) {
  if (!err) {
    fs.writeFile(path, ...);
  }
});
like image 147
kdotphil Avatar answered Sep 17 '25 01:09

kdotphil


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 slice to omit the file itself.

like image 25
trip41 Avatar answered Sep 17 '25 03:09

trip41