Example of Node. js readline Reading and Writing File Content line by line, node. jsreadline
This article describes the two implementation methods of reading data row by row using readline. The details are as follows:
What is Readline?
Readline is an encapsulated module for implementing standard input and output in Node. js. With this module, we can read data streams row by row. You can use require ("readline") to reference a module.
As follows:
1.log on the left is the source file
1. readline. log on the right is the copied file.
Below is the command line output
Method 1:
Var readline = require ('readline'); var fs = require ('fs'); var OS = require ('OS'); var fReadName = '. /1. log'; var fWriteName = '. /1. readline. log'; var fRead = fs. createReadStream (fReadName); var fWrite = fs. createWriteStream (fWriteName); var objReadline = readline. createInterface ({input: fRead, // This is another replication method, so that on ('line') does not have to call fWrite. write (line). We recommend that you use it when only copying files. // However, the index count sodino.com/output: fWrite, // terminal: true} will be calculated at the end of the file }); var index = 1; objReadline. on ('line', (line) => {var tmp = 'line' + index. toString () + ':' + line; fWrite. write (tmp + OS. EOL); // The console of the next line. log (index, line); index ++;}); objReadline. on ('close', () => {console. log ('readline close... ');});
Method 2:
Var readline = require ('readline'); var fs = require ('fs'); var OS = require ('OS'); var fReadName = '. /1. log'; var fWriteName = '. /1. readline. log'; var fRead = fs. createReadStream (fReadName); var fWrite = fs. createWriteStream (fWriteName); var enableWriteIndex = true; fRead. on ('end', () => {console. log ('end'); enableWriteIndex = false;}); var objReadline = readline. createInterface ({input: fRead, output: fWrite, terminal: true}); var index = 1; fWrite. write ('line' + index. toString () + ':'); objReadline. on ('line', (line) => {console. log (index, line); if (enableWriteIndex) {// because readline: output is the on ('line') event called after the first write, // The row number does not need to be written when the file has been read... sodino.com index ++; var tmp = 'line' + index. toString () + ':'; fWrite. write (tmp) ;}}); objReadline. on ('close', () => {console. log ('readline close... ');});
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.