Node.js create folder or use existing

后端 未结 14 1433
暖寄归人
暖寄归人 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:43

    I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

    LAST UPDATE :

    In v10.12.0, NodeJS impletement recursive options :

    // Create recursive folder
    fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
    

    UPDATE :

    // Get modules node
    const fs   = require('fs');
    const path = require('path');
    
    // Create 
    function mkdirpath(dirPath)
    {
        if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
        {
            try
            {
                fs.mkdirSync(dirPath);
            }
            catch(e)
            {
                mkdirpath(path.dirname(dirPath));
                mkdirpath(dirPath);
            }
        }
    }
    
    // Create folder path
    mkdirpath('my/new/folder/create');
    

提交回复
热议问题