Search code examples
node.jsfs

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


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!


Solution

  • Since node 10 you can create the entire path with a single command by setting options.recursive to true:

    if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true });
    }
    

    https://nodejs.org/api/fs.html#fsmkdirsyncpath-options