Úkoly

NodeJS CLI program

Using node18, how to write the simplest command line program in javascript, that uses stdin and stdout?

ChatGPT advice

To create a simple command-line program in Node.js that uses stdin and stdout, you can follow these steps:

  1. Make sure you have Node.js installed on your system.
  2. Create a new directory for your project and navigate to it in your terminal.
  3. Create a JavaScript file for your program. Let's call it simple-cli.js.
  4. In simple-cli.js, you can use the process.stdin and process.stdout streams to read from stdin and write to stdout. Here's a basic example that reads input from stdin and writes it back to stdout:
// Import the 'readline' module to handle input and output
const readline = require('readline');
 
// Create an interface for reading from stdin and writing to stdout
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
 
// Prompt the user for input
rl.question('Please enter something: ', (input) => {
  // Process the input
  const output = `You entered: ${input}`;
 
  // Write the output to stdout
  console.log(output);
 
  // Close the readline interface
  rl.close();
});

Save the file and run your program from the command line:

node simple-cli.js

That's it! You've created a simple command-line program in JavaScript using stdin and stdout. You can customize and expand upon this basic template to perform more complex tasks as needed.