fs.writeFile in a promise, asynchronous-synchronous stuff

前端 未结 10 1506
清歌不尽
清歌不尽 2020-11-30 22:49

I need some help with my code. I\'m new at Node.js and have a lot of trouble with it.

What I\'m trying to do:

1) Fetch a .txt with Amazon products (ASINs) ;<

10条回答
  •  自闭症患者
    2020-11-30 23:23

    What worked for me was fs.promises.

    Example One:

    const fs = require("fs")
    
    fs.promises
      .writeFile(__dirname + '/test.json', "data", { encoding: 'utf8' })
      .then(() => {
        // Do whatever you want to do.
        console.log('Done');
      });
    

    Example Two. Using Async-Await:

    const fs = require("fs")
    
    async function writeToFile() {
      await fs.promises.writeFile(__dirname + '/test-22.json', "data", {
        encoding: 'utf8'
      });
    
      console.log("done")
    }
    
    writeToFile()
    

提交回复
热议问题