I have a need to store data in variable, store whole variable to a file and then read it from a file.
How to achieve that with Java script?
Tried with:
fs.writeFileSync('/tmp/data.txt', JSON.stringify(objectData));
fs.readFile('/tmp/data.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
But second part is executing before file write finishes giving either corrupted data or partial one.
How to achieve above scenario?
I think in your case it's better if you use fs.writeFile as described here , to ensure if your write has been done and then read your file:
fs.writeFile('/tmp/data.txt', JSON.stringify(objectData), (err) => {
if (err) throw err;
console.log('The file has been saved!');
fs.readFile('/tmp/data.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.