fs.writeFile in a promise, asynchronous-synchronous stuff

前端 未结 10 1353
清歌不尽
清歌不尽 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:15

    Use fs.writeFileSync inside the try/catch block as below.

    `var fs = require('fs');
     try {
         const file = fs.writeFileSync(ASIN + '.json', JSON.stringify(results))
         console.log("JSON saved");
         return results;
     } catch (error) {
       console.log(err);
      }`
    
    0 讨论(0)
  • 2020-11-30 23:19

    Update Sept 2017: fs-promise has been deprecated in favour of fs-extra.


    I haven't used it, but you could look into fs-promise. It's a node module that:

    Proxies all async fs methods exposing them as Promises/A+ compatible promises (when, Q, etc). Passes all sync methods through as values.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2020-11-30 23:24

    say

    const util = require('util')
    const fs_writeFile = util.promisify(fs.writeFile)
    

    https://nodejs.org/api/util.html#util_util_promisify_original

    this is less prone to bugs than the top-voted answer

    0 讨论(0)
  • 2020-11-30 23:29

    If you want to import the promise based version of fs as an ES module you can do:

    import { promises as fs } from 'fs'
    
    await fs.writeFile(...)
    

    As soon as node v14 is released (see this PR), you can also use

    import { writeFile } from 'fs/promises'
    
    0 讨论(0)
  • 2020-11-30 23:30

    Finally, the latest node.js release v10.3.0 has natively supported fs promises.

    const fsPromises = require('fs').promises; // or require('fs/promises') in v10.0.0
    fsPromises.writeFile(ASIN + '.json', JSON.stringify(results))
      .then(() => {
        console.log('JSON saved');
      })
      .catch(er => {
        console.log(er);
      });
    

    You can check the official documentation for more details. https://nodejs.org/api/fs.html#fs_fs_promises_api

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