JS Reference
Service Workers
ESModule Tips
NodeJS Tips
Javascript Tips
NodeJS file readwrite line by line
Using file stream
Node JS File system - Read and write line by line
Nodejs file read and write by line
Info
The sample code is below to write line by line after reading the file line by line as a stream.
Sample Code
index.html
const fs = require('fs');
const readline = require('readline');
// Define input and output file paths
const inputFile = 'input.txt';
const outputFile = 'output.txt';
// Create a readable stream for the input file
const readStream = fs.createReadStream(inputFile);
// Create a writable stream for the output file
// The 'w' flag will create the file if it doesn't exist or overwrite it if it does
const writeStream = fs.createWriteStream(outputFile, { flags: 'w' });
// Create a readline interface to process the input stream line by line
const rl = readline.createInterface({
input: readStream,
crlfDelay: Infinity // Treats all instances of CR LF as a single line break
});
// Listen for the 'line' event on the readline interface
rl.on('line', (line) => {
// Process the line (optional, you can modify 'line' here)
const processedLine = line.toUpperCase(); // Example processing: convert to uppercase
// Write the processed line to the output file, followed by a newline character
writeStream.write(processedLine + '\n');
});
// Listen for the 'close' event on the readline interface, indicating the input file is fully read
rl.on('close', () => {
console.log('Finished reading and writing files line by line.');
// Close the writable stream when done
writeStream.end();
});
// Handle potential errors on the streams
readStream.on('error', (err) => {
console.error('Error reading file:', err);
});
writeStream.on('error', (err) => {
console.error('Error writing file:', err);
});