1
\$\begingroup\$

I wrote this function that takes 2 arguments - the path to an existing file - file, and the newRoot name. The function splits the new path into directories, replaces the first directory in the path to the file with newRoot, , then loops trough all the directories checking if the director exists, and if not creates one:

/**
 * Creates directories for the file in newRoot if not there
 * @param {String} file - the path to the file
 * @param {String} newRoot - the new root directory for the file
 */
functions.makeDirectory = (file, newRoot) => {
 let dirPath = path.dirname(file);
 let directories = dirPath.split('/');
 let currentPath = '';
 directories[0] = newRoot;
 directories.map(directory => {
 currentPath = path.join(currentPath, directory);
 if(!fs.existsSync(currentPath)) {
 fs.mkdirSync(currentPath);
 };
 });
};

The string operations here seem a bit redundat, but I can't figure out how to get rid of them. Is there a more optimal solution for this or am I on the right track?

Would it increase performance to rewrite the fs function as a promise?

asked Nov 26, 2016 at 10:43
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

There are util libraries for this:fs-extra.

From its doc:

mkdirs(dir, callback) Creates a directory. If the parent hierarchy doesn't exist, it's created. Like mkdir -p.

Alias: mkdirp()

Sync: mkdirsSync() / mkdirpSync()

Examples:

var fs = require('fs-extra')
fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
 if (err) return console.error(err)
 console.log("success!")
})
fs.mkdirsSync('/tmp/another/path')

If you write function as a promise it would enable other code to run between each step of your function (eg. between each subdir being created) so it will not block other code like sending some request after calling this function.

answered Nov 26, 2016 at 11:15
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.