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

前端 未结 18 1167
臣服心动
臣服心动 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:55

    I had to create sub-directories if they didn't exist. I used this:

    const path = require('path');
    const fs = require('fs');
    
    function ensureDirectoryExists(p) {
        //console.log(ensureDirectoryExists.name, {p});
        const d = path.dirname(p);
        if (d && d !== p) {
            ensureDirectoryExists(d);
        }
        if (!fs.existsSync(d)) {
            fs.mkdirSync(d);
        }
    }
    

提交回复
热议问题