Create Directory When Writing To File In Node.js

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

    Node > 10.12.0

    fs.mkdir now accepts a { recursive: true } option like so:

    // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
    fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
      if (err) throw err;
    });
    

    or with a promise:

    fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
    

    Node <= 10.11.0

    You can solve this with a package like mkdirp or fs-extra. If you don't want to install a package, please see Tiago Peres França's answer below.

提交回复
热议问题