Use NodeJS and write a program that reads streamed data from stdin.
- User
Use NodeJS and write a program that reads streamed data from stdin.
- Assistant
Use NodeJS and write a program that reads streamed data from stdin.
Certainly! Below is a simple Node.js program that reads streamed data from stdin. This program listens for incoming data, processes it line by line, and handles end-of-input gracefully. Additionally, I'll provide explanations and examples of how you can use and extend this program.
readline ModuleThe readline module in Node.js provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. This is particularly useful for processing input line by line.
// streamReader.js
const readline = require('readline');
// Create an interface to read lines from stdin
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false // Set to false to prevent readline from taking control of the output
});
// Event listener for each line of input
rl.on('line', (line) => {
// Process the incoming line
console.log(`Received: ${line}`);
});
// Event listener for end of input (e.g., Ctrl+D)
rl.on('close', () => {
console.log('No more data.');
process.exit(0);
});
// Optional: Handle errors
rl.on('error', (err) => {
console.error(`Error: ${err}`);
process.exit(1);
});
Save the Code: Save the above code to a file named streamReader.js.
Run the Program: You can run the program using Node.js and provide input via the terminal or by piping data from another command.
Interactive Input:
node streamReader.js
Type lines of text and press Enter after each line. To signal the end of input, press Ctrl+D (on Unix/Linux/macOS) or Ctrl+Z followed by Enter (on Windows).
Example:
$ node streamReader.js
Hello, World!
Received: Hello, World!
This is a test.
Received: This is a test.
^D
No more data.
Piping Data from a File:
Suppose you have a file named input.txt with the following content:
Line 1
Line 2
Line 3
You can pipe this file into the program:
cat input.txt | node streamReader.js
Output:
Received: Line 1
Received: Line 2
Received: Line 3
No more data.
Piping Data from Another Command:
For example, you can pipe the output of echo:
echo -e "Apple\nBanana\nCherry" | node streamReader.js
Output:
Received: Apple
Received: Banana
Received: Cherry
No more data.
Importing readline:
const readline = require('readline');
The readline module provides a way to read data from a Readable stream (like process.stdin) one line at a time.
Creating the Interface:
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
input: The stream to read from (process.stdin).output: The stream to write output to. Set to process.stdout if you want to provide prompts or echoes.terminal: Set to false to indicate that the output is not a terminal (affects how input is processed).Listening for line Events:
rl.on('line', (line) => {
console.log(`Received: ${line}`);
});
Every time a new line is entered (terminated by a newline character), the callback is invoked with the line as its argument.
Handling End of Input with close Event:
rl.on('close', () => {
console.log('No more data.');
process.exit(0);
});
The close event is emitted when there is no more data to read (e.g., when the user signals end-of-input with Ctrl+D).
Error Handling:
rl.on('error', (err) => {
console.error(`Error: ${err}`);
process.exit(1);
});
It's good practice to handle possible errors to prevent the program from crashing unexpectedly.
process.stdin DirectlyIf you prefer not to use the readline module, you can interact directly with process.stdin, which is a Readable stream. Here's how you can do it:
// streamReaderDirect.js
// Set the encoding to handle string input
process.stdin.setEncoding('utf8');
// Event listener for incoming data
process.stdin.on('data', (chunk) => {
// Process the incoming chunk
console.log(`Received chunk: ${chunk}`);
});
// Event listener for end of input
process.stdin.on('end', () => {
console.log('No more data.');
process.exit(0);
});
// Optional: Handle errors
process.stdin.on('error', (err) => {
console.error(`Error: ${err}`);
process.exit(1);
});
The usage is similar to the previous example. You can provide input interactively or pipe data from a file or another command.
Setting Encoding:
process.stdin.setEncoding('utf8');
This ensures that the data received is in string format rather than raw Buffer objects.
Listening for data Events:
process.stdin.on('data', (chunk) => {
console.log(`Received chunk: ${chunk}`);
});
The data event is emitted whenever the stream receives data. Unlike the readline approach, data can arrive in chunks that don't necessarily align with line boundaries.
Handling End of Input with end Event:
process.stdin.on('end', () => {
console.log('No more data.');
process.exit(0);
});
The end event signifies that there is no more data to read.
Error Handling:
Similar to the readline example, it's important to handle potential errors.
readline Module: Best when you need to process input line by line, such as reading commands from a user or parsing a text file line by line.
Direct process.stdin Handling: Suitable for scenarios where data does not naturally break into lines, such as binary data or when you need more control over how data is buffered and processed.
Depending on your use case, you might want to extend the program to perform various tasks with the incoming data. Here are a few ideas:
Data Transformation: Modify the incoming data before outputting it.
rl.on('line', (line) => {
const transformed = line.toUpperCase();
console.log(`Transformed: ${transformed}`);
});
Filtering Data: Only process lines that meet certain criteria.
rl.on('line', (line) => {
if (line.includes('error')) {
console.log(`Error found: ${line}`);
}
});
Aggregating Data: Collect data over time and perform actions once all data is received.
let lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.on('close', () => {
console.log('All lines received:', lines);
// Perform further processing here
});
Streaming to Another Service: Forward the received data to another service or API.
const axios = require('axios');
rl.on('line', async (line) => {
try {
await axios.post('https://example.com/api/data', { data: line });
console.log(`Sent: ${line}`);
} catch (error) {
console.error(`Failed to send: ${line}`, error);
}
});
Reading streamed data from stdin in Node.js can be accomplished efficiently using either the readline module for line-by-line processing or by handling the process.stdin stream directly for more granular control. The examples provided should give you a solid foundation to build upon based on your specific requirements.
Feel free to ask if you have any further questions or need additional functionality!
Not yet included in a published release.