How to take input in Node.js / Javascript from file or stdin.

Revision en8, by RohitKaushal, 2020-01-26 11:58:34

javascript : To use in Codeforces

Input
readline() Reads one line from stdin.
to get some space separated values from a line:

var num = readline().split(" ").map(x => parseInt(x)); // num will be an array [1,2,3]
var x = num[0]; // to store values in different variables. 
var y= num[1];
var z= num[2];


var num2= readline(); // reads next line.

Output
print(x); // with auto '\n' (newline)

Refer this submission for a sample program submission.




Node.js : To run your programs locally and submit on CF

readline() do not work by default if you try to use it locally on your computer.

Write this header code in the beginning of your js code

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();


function main() {
    const x = readline();
    var line2 = readline(); 
    
    foo(x);
    foo(line2);
}
function foo(x) {
    process.stdout.write("hello: ");   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

Testing Locally

paste your input in a text file input.txt
then
$ cat input.txt | node main.js output on console.
$ cat input.txt | node main.js > output.txt output in file.

you can also make a sublime-build file for this and then just press Ctrl+B
Tools> Build System > new build system > nodejs.sublime-build
{ "shell_cmd": "cat $file_path/input.txt | node $file > $file_path/output.txt" }

Here is a Sample Image :)

Tags nodejs, javascript, input, stdin, codeforce javascript

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en8 English RohitKaushal 2020-01-26 11:58:34 742 Tiny change: 'ion.**\n\n\n\n\n###T' -> 'ion.**\n\n<hr>\n\n\n###T'
en7 English RohitKaushal 2020-01-03 09:18:55 3
en6 English RohitKaushal 2019-10-17 12:19:26 7 Tiny change: 'cb52.png) proof. :)\n ' -> 'cb52.png) :)\n '
en5 English RohitKaushal 2019-09-14 19:49:10 107
en4 English RohitKaushal 2019-09-14 19:37:07 159
en3 English RohitKaushal 2019-09-08 16:55:46 882 Tiny change: 'orces\n\n```readline()``` Reads on' -> 'orces\n\n`readline()` Reads on'
en2 English RohitKaushal 2019-09-06 23:08:34 0 (published)
en1 English RohitKaushal 2019-09-06 23:07:41 1459 Initial revision (saved to drafts)