Introduction
When solving coding problems on online judges, one of the essential tasks is to read input from the standard input stream (stdin
). In some programming languages, such as Python and Java, reading input from stdin
is relatively straightforward. However, in Node.js, it can be challenging and cumbersome, especially for beginners.
In this tutorial, we’ll show how read input from stdin
in Node.js, and we’ll provide a sample code that you can use as a template for your coding problems.
I’ve seen many template code for taking input in NodeJS. But all of them are not useable by beginners.
Reading input from stdin in Node.js
Use this template written by me:
let _inputData="",_inputArray=[],_count=-1;function input(){let n=_inputArray[_count];return _count++,n}process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){_inputData+=n})),process.stdin.on("end",(function(){_inputArray=_inputData.split("\n"),input(),main()}));
// You need to code in this main function.
function main() {
let a = input();
a = parseInt(a);
console.log(a);
}
Here, to read a line of input, just call the function input()
.
input()
function will return a string
. You can simply apply NodeJS method like parseInt()
to convert it to int
For each call, input()
function will return one line of the stdin. If there’s no more input to read, it’ll return undefined
I’ve minimized this code so it doesn’t look like a mess.
If you want to see the commented long code:
Also, I’ve solved some problems using this template in toph.co
You can see those if you’re still confused on how to use this template.
My NodeJS submissions: Submissions | Toph
Use the code snippets provided in this tutorial as a starting point for your own solutions, and happy coding!
Author:
Nusab Taha