The processAsStream function provides a way to read data from a file or stdin, split it into lines based on a regular expression, and process each line through a callback. The results of the callback are then written to an output stream.
Input Sources
- If
options.filename is set to '-', the function reads from process.stdin. - Otherwise, it creates a read stream from the file path provided in
options.filename.
Callback Behavior
The options.callback is executed for every line. It receives the following arguments:
line: The raw string content of the current line.lineNumber: The zero-based index of the current line.columns: An array of strings created by splitting the line using options.colSeparatorRegex.
Return Values of the Callback:
false: The line is skipped, and no newline is written to the output stream.string or number: The value is converted to a string and written to options.outStream, followed by the options.lineSeparator on the next line.- Any other type: The original
line is written to options.outStream, followed by the options.lineSeparator on the next line.
Options Object
| Key | Description |
|---|
filename | Path to the input file, or '-' for stdin |
lineSeparatorRegex | Regex used by the split module to identify line boundaries |
colSeparatorRegex | Regex used to split the line into columns |
outStream | A writable stream where processed results are sent |
lineSeparator | The string used to separate lines in the output stream |
callback | The function executed for each line |
context | (Optional) The this context for the callback function |
const processAsStream = require('./lib/process-as-stream');
const fs = require('fs');
const options = {
filename: 'input.txt',
lineSeparatorRegex: /\r?\n/,
colSeparatorRegex: /,/,
outStream: fs.createWriteStream('output.txt'),
lineSeparator: '\n',
callback: function(line, lineNumber, columns) {
// Process columns
const transformed = columns[0].toUpperCase();
return transformed;
}
};
processAsStream(options, (err) => {
if (err) console.error(err);
else console.log('Processing complete');
});