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

前端 未结 18 1164
臣服心动
臣服心动 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条回答
  •  猫巷女王i
    2020-11-30 16:51

    fs.exist() is deprecated. So I have used fs.stat() to check the directory status. If the directory does not exist fs.stat() throw an error with message like 'no such file or directory'. Then I have created a directory.

    const fs = require('fs').promises;
        
    const dir = './dir';
    fs.stat(dir).catch(async (err) => {
      if (err.message.includes('no such file or directory')) {
        await fs.mkdir(dir);
      }
    });
    

提交回复
热议问题