1

Can it be said that fs promise writeFile and fs writeFileSync are the same thing? or rather, would behave the same way?

const fs = require('fs')
const fsProm = require ('fs').promises

//write file sync
fs.writeFileSync(filePath, data)

write file promise

fsProm.writeFile(filePath, data)

can any one please explain?

Also, fs promises writefile returns a promise, how do you check if the write was a success, and write a conditional statement based on that?

if (fsProm.writeFile === undefined) {
 //do something
} else {
  //do something else
}

how do i check if the operation was a success, and write a conditional statement based on that??

payiyke
  • 19
  • 3

1 Answers1

0

Can it be said that fs promise writeFile and fs writeFileSync are the same thing? or rather, would behave the same way?

fs.writeFileSync blocks the process. So in that way, they don't behave the same way.

Also, fs promises writefile returns a promise, how do you check if the write was a success, and write a conditional statement based on that?

try {
  await fsProm.writeFile(filePath, data);
  //do something
} catch (err) {
  //do something else
}

Finally, this is the most current recommendation for importing fs/promises:

// If you're using CommonJS
const fsPromises = require('node:fs/promises');

// If you're using ESM
import * as fsPromises from 'node:fs/promises';
Evert
  • 93,428
  • 18
  • 118
  • 189
  • well, actually, in my code, i m trying to use nodemailer to send the written data to an email address, if you don't mind, how could i combine both using the try-catch method? – payiyke Feb 19 '23 at 07:39
  • @payiyke open a new question. – Evert Feb 19 '23 at 21:05