Create Directory When Writing To File In Node.js

前端 未结 9 1611
情话喂你
情话喂你 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:36

    If you don't want to use any additional package, you can call the following function before creating your file:

    var path = require('path'),
        fs = require('fs');
    
    function ensureDirectoryExistence(filePath) {
      var dirname = path.dirname(filePath);
      if (fs.existsSync(dirname)) {
        return true;
      }
      ensureDirectoryExistence(dirname);
      fs.mkdirSync(dirname);
    }
    

提交回复
热议问题