Create Directory When Writing To File In Node.js

前端 未结 9 1420
情话喂你
情话喂你 2021-01-30 09:44

I\'ve been tinkering with Node.js and found a little problem. I\'ve got a script which resides in a directory called data. I want the script to write some data to

9条回答
  •  难免孤独
    2021-01-30 10:19

    Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-frança fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

    function mkdirp(filepath) {
        var dirname = path.dirname(filepath);
    
        if (!fs.existsSync(dirname)) {
            mkdirp(dirname);
        }
    
        fs.mkdirSync(filepath);
    }
    

提交回复
热议问题