node js write read string to file code example
Example: node js write read string to file
// basic read-write string from-to file with node.js
var fs = require('fs');
var opath = 'test.txt';
var ostring = 'Hello!'
fs.writeFileSync(opath, ostring, 'utf8');
var istring = fs.readFileSync('test.txt').toString();
console.log(istring);
// with error handling and logging:
fs.readFile('test.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
});
// or fs.readFileSync() or use streams for large files
// for better memory consumption and execution speed
// https://nodejs.dev/learn/reading-files-with-nodejs