In: Computer Science
Using Node.js, show how you would read a file and and write out its contents to a new file in reverse order.
As an example, if the source file had:
Roses are red,
Violets are blue.
If the Trump administration continues to lose cabinet members,
I will not be sad. Boo hoo hoo.
The destination file would have:
I will not be sad. Boo hoo hoo.
If the Trump administration continues to lose cabinet members, Violets are blue.
Roses are red,
First install package:
Install reverse-line-reader and ga package using
npm i reverse-line-reader fs
Code:
var lineReader = require('reverse-line-reader');
var fs = require("fs");
var content = []
// read all lines from source file and push it to array
lineReader.eachLine('source.txt', function(line) {
content.push(line);
}).then(function () {
//write array to destination file
fs.writeFile('destination.txt',content.join('\n'),function (err) {
console.log(err ? 'Error :'+err : 'written successfully') }
);
});
Output:
source.text file:
After executing above code:
destination.txt file: