Are there some advantages of one of this options?
1.
const fs = require('fs')
const testFunc1 = async () => {
fs.writeFileSync('text.txt', 'hello world')
}
2.
const fs = require('fs')
const util = require('util')
const writeFilePromisified = util.promisify(fs.writeFile)
const testFunc2 = async () => {
await writeFilePromisified('text.txt', 'hello world')
}
I am aware the difference betweeen writeFile and writeFileSync. The question is are there some diffs between promisses that return testFunc1 and testFunc2. So ist it the same to calling testFunc1.then(...) // or await testFunc1 or testFunc2.then(...) // or await testFunc2
These both promisses will be fullfilled when file writing is done.
The fs. writeFileSync() is a synchronous method & creates a new file if the specified file does not exist while fs. writeFile() is an asynchronous method.
writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.
writeFileSync() to write data in files. The latter is a synchronous method for writing data in files. fs. writeFileSync() is a synchronous method, and synchronous code blocks the execution of program.
Reading filesThe fs. readFile() method lets you asynchronously read the entire contents of a file. It accepts up to three arguments: The path to the file.
fs
already contains promisified API that doesn't need promisify
.
const fsPromises = require("fs/promises");
await fsPromises.writeFile(file, data[, options])
Asynchronous promise-based version requires to use it as a part of promise-based control flow, while synchronous version doesn't impose this requirement.
Asynchronous readFile
/writeFile
is non-blocking, while synchronous readFileSync
/writeFileSync
is blocking but allows to complete a job faster. This may be noticeable during intensive IO operations.
To illustrate the difference between two promises that returns functions:
const fs = require('fs')
const util = require('util')
const testFunc1 = async () => {
fs.writeFileSync('text.txt', 'hello world')
console.log('file write done with writeFileSync')
}
const writeFilePromisified = util.promisify(fs.writeFile)
const testFunc2 = async () => {
await writeFilePromisified('text.txt', 'hello world')
console.log('file write done with promisified writeFile')
}
console.log('start test1')
testFunc1().then(() => {
console.log('promise 1 is fullfiled')
})
console.log('start test2')
testFunc2().then(() => {
console.log('promise 2 is fullfiled')
})
console.log('stop')
Output would be:
start test1
file write done with writeFileSync
start test2
stop
promise 1 is fullfiled
file write done with promisified writeFile
promise 2 is fullfiled
So like estus said testFunc1 blocks the execution of the main thread. testFunc2 do not block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With