Node.js create folder or use existing

后端 未结 14 1462
暖寄归人
暖寄归人 2020-12-04 06:43

I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdi

14条回答
  •  一个人的身影
    2020-12-04 07:45

    Here is the ES6 code which I use to create a directory (when it doesn't exist):

    const fs = require('fs');
    const path = require('path');
    
    function createDirectory(directoryPath) {
      const directory = path.normalize(directoryPath);
    
      return new Promise((resolve, reject) => {
        fs.stat(directory, (error) => {
          if (error) {
            if (error.code === 'ENOENT') {
              fs.mkdir(directory, (error) => {
                if (error) {
                  reject(error);
                } else {
                  resolve(directory);
                }
              });
            } else {
              reject(error);
            }
          } else {
            resolve(directory);
          }
        });
      });
    }
    
    const directoryPath = `${__dirname}/test`;
    
    createDirectory(directoryPath).then((path) => {
      console.log(`Successfully created directory: '${path}'`);
    }).catch((error) => {
      console.log(`Problem creating directory: ${error.message}`)
    });
    

    Note:

    • In the beginning of the createDirectory function, I normalize the path to guarantee that the path seperator type of the operating system will be used consistently (e.g. this will turn C:\directory/test into C:\directory\test (when being on Windows)
    • fs.exists is deprecated, that's why I use fs.stat to check if the directory already exists
    • If a directory doesn't exist, the error code will be ENOENT (Error NO ENTry)
    • The directory itself will be created using fs.mkdir
    • I prefer the asynchronous function fs.mkdir over it's blocking counterpart fs.mkdirSync and because of the wrapping Promise it will be guaranteed that the path of the directory will only be returned after the directory has been successfully created

提交回复
热议问题