NodeJS read/write text files

Posted by Joe Enos on April 26, 2021 · 3 mins read

"use strict";

(function() {
var fs = require("fs");
var readline = require("readline");

fs.readFile("input.json", function(error, data) {
var obj = JSON.parse(data);
fs.writeFile("output.json", JSON.stringify(obj), function(err) {
if (err) {
console.log("Error: " + err);
} else {
console.log("Saved");
}
});
});

(function() {
var outputStream = fs.createWriteStream("output.txt");

var lineReader = readline.createInterface({
input: fs.createReadStream("input.txt")
});
lineReader.on("line", function(line) {
console.log("Line: " + line);
outputStream.write(line + "\r\n");
});
lineReader.on("close", function() {
outputStream.end();
});
})();
})();