How To Read Data From Terminal In Javascript With Node.js | letsbug
This is going to be short article on how you can make command line interface with node.js in Javascript. If you have been working with node.js you known that you can write something to the console with console.log method from you javascript file. But read some data from the terminal is something different, it is very in some other languages like c and python.
In javascript with node.js you have to do a little work. Start by requiring the readline module which is built in the node.js and then we call the method createInterface with process standard input and output as its parameter. Now basic foundation is done over here.
Now we have lots of different methods that can be used but are going to use the question method which will prompt user to with a question to enter some data and then reads that data and returns us that data in a callback function.
Then will can use that data to process it and do something with it. and at last we close the interface with close method. Below is the code for the same.
Read Data From The Terminal In Javascript & Node.js
Code:
const readline = require('readline');const rl = readline.createInterface({input: process.stdin,output: process.stdout});rl.question("What is your name? ", (answer) => {console.log(`Hello ${answer}`)rl.close();})
Output:
question in the terminal |
answer to the question |
response |
Comments
Post a Comment