I have this code which is supposed to write data in text file:
const test = [
'test1',
'test2'
]
fs.writeFile('file.txt', test, {flag: "a"}, err => {
if (err) throw err
})
The problem is that code works without errors, but there is no data in file. If I just put and execute this piece of code in some test file, it works correctly, but not in function, where this code is supposed to be. What's wrong? Why there is no data in file if I execute code in function, but everything works correctly, when I execute it in test file?
Here is the code of function:
const fs = require("fs");
(async () => {
const test = [
'test1',
'test2'
]
fs.writeFile('file.txt', test, {flag: "a"}, err => {
if (err) throw err
})
process.exit(1);
} catch (e) {
console.log('error: ', e)
process.exit(1)
}
})()
CodePudding user response:
You're missing the "try" part of your try/catch.
You're also exiting the script before the file is written.
try writeFileSync
instead.
const fs = require("fs");
(async() => {
const test = [
'test1',
'test2'
]
try {
fs.writeFileSync('file.txt', test, {
flag: "a"
});
process.exit(1);
} catch (e) {
console.log('error: ', e)
process.exit(1)
}
})()