Create Directory When Writing To File In Node.js

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

    Same answer as above, but with async await and ready to use!

    const fs = require('fs/promises');
    const path = require('path');
    
    async function isExists(path) {
      try {
        await fs.access(path);
        return true;
      } catch {
        return false;
      }
    };
    
    async function writeFile(filePath, data) {
      try {
        const dirname = path.dirname(filePath);
        const exist = await isExists(dirname);
        if (!exist) {
          await fs.mkdir(dirname, {recursive: true});
        }
        
        await fs.writeFile(filePath, data, 'utf8');
      } catch (err) {
        throw new Error(err);
      }
    }
    

    Example:

    (async () {
      const data = 'Hello, World!';
      await writeFile('dist/posts/hello-world.html', data);
    })();
    

提交回复
热议问题