How to read and write file contents line by line by readline in Node.js
This article mainly explains "how to read and write file contents line by line in readline in Node.js". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to read and write file contents line by line in readline in Node.js".
What is Readline?
Readline is an encapsulated module in Node.js that implements standard input and output. Through this module, we can read the data stream line by line. Modules can be referenced using require ("readline").
The effect picture is as follows:
1.log on the left is the source file
The 1.readline.log on the right is the copied file.
The following is the command line output
Implementation 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 way of copying, so that fWrite.write (line) does not have to be called in on ('line'). It is recommended to use / / but an extra index count sodino.com / / output: fWrite, / / terminal: true} at the end of the file is recommended when simply copying the file; var index = 1 ObjReadline.on ('line', (line) = > {var tmp =' line' + index.toString () +':'+ line; fWrite.write (tmp + os.EOL); / / next line console.log (index, line); index + +;}); objReadline.on ('close', () = > {console.log (' readline close...');})
The second way of implementation:
Var readline = require ('readline'); var fs = require (' fs'); var os = require ('os'); var fReadName ='. / 1.loglog; 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 an on ('line') event that is written first and then called, / / there is no need to write line numbers when the file has been read. Sodino.com index + +; var tmp = 'line' + index.toString () +':'; fWrite.write (tmp);}}); objReadline.on ('close', () = > {console.log (' readline close...');}). At this point, I believe you have a deeper understanding of "how to read and write file contents line by line in Node.js". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!