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) ;<
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);
}`
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.
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()
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
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'
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