Create Directory When Writing To File In Node.js

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

    first taking the full path including directory and extracting the directory

    //Just for the sake of example
    cwd=process.cwd()
    filendir=path.resolve(cwd,'_site/assets/text','node.txt')
    
    // Extracting directory name
    mkdir=path.dirname(filendir)
    

    Now make the directory, add option recursive:true as stated by @David Weldon

    fs.mkdirSync(mkdir,{recursive:true})
    

    Then make the file

    data='Some random text'
    fs.writeFileSync(filendir,data)
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-30 10:36

    Shameless plug alert!

    You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath

    0 讨论(0)
提交回复
热议问题