Two ways to read files line by line in nodejs

Two ways to read files line by line in nodejs

  1. By way of readline

    const fs = require('fs');
    const readline  = require('readline');
    
    let rl = readline.createInterface({
          
          
      input: fs.createReadStream("./11.txt")
    })
    rl.on('line', line => {
          
          
      console.log(line);
    })
    
  2. By way of stream

    Idea: In the form of stream, read one byte at a time, and then judge whether this subsection is a newline character (the newline character in mac is 0xa0)

    If not, save the byte in a temporary array, if so, transcode these arrays into utf8 in the form of Buffer

    The following case is: read a file, then add "" to each line, put it into an array, and then write it into a new file.

    const fs = require("fs");
    
    let readStream = fs.createReadStream("./11.txt");
    let writeStream = fs.createWriteStream("./11_11.txt");
    let buffer = [];
    
    function writeFileWithLine(line, isLastLine) {
    	writeStream.write('\t"');
    	writeStream.write(line);
    	if (isLastLine) {
        writeStream.write('"\n')
    	} else {
    		writeStream.write('",\n');
    	}
    }
    writeStream.write("[\n");
    readStream.on("readable", () => {
    	while ((char = readStream.read(1)) !== null) {
    		if (char[0] === 0x0a) {
    			writeFileWithLine(Buffer.from(buffer).toString(), false);
    			buffer.length = 0;
    		} else {
    			buffer.push(char[0]);
    		}
    	}
    });
    readStream.on("end", () => {
    	writeFileWithLine(Buffer.from(buffer).toString(), true);
    	writeStream.write("]");
    });
    
    
    
    

Guess you like

Origin blog.csdn.net/mochenangel/article/details/122743815