How to create a directory if it doesn't exist using Node.js?

前端 未结 18 1158
臣服心动
臣服心动 2020-11-30 16:03

Is this the right way to create a directory if it doesn\'t exist. It should have full permission for the script and readable by others.

var dir = __dirname +         


        
18条回答
  •  被撕碎了的回忆
    2020-11-30 16:50

    The mkdir method has the ability to recursively create any directories in a path that don't exist, and ignore the ones that do.

    From the Node v10/11 docs:

    // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
    fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
        if (err) throw err;
    });
    

    NOTE: You'll need to import the built-in fs module first.

    Now here's a little more robust example that leverages native ES Modules (with flag enabled and .mjs extension), handles non-root paths, and accounts for full pathnames:

    import fs from 'fs';
    import path from 'path';
    
    createDirectories(pathname) {
       const __dirname = path.resolve();
       pathname = pathname.replace(/^\.*\/|\/?[^\/]+\.[a-z]+|\/$/g, ''); // Remove leading directory markers, and remove ending /file-name.extension
       fs.mkdir(path.resolve(__dirname, pathname), { recursive: true }, e => {
           if (e) {
               console.error(e);
           } else {
               console.log('Success');
           }
        });
    }
    

    You can use it like createDirectories('/components/widget/widget.js');.

    And of course, you'd probably want to get more fancy by using promises with async/await to leverage file creation in a more readable synchronous-looking way when the directories are created; but, that's beyond the question's scope.

提交回复
热议问题