Create Directory When Writing To File In Node.js

前端 未结 9 1407
情话喂你
情话喂你 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)
    

提交回复
热议问题