Archive

Posts Tagged ‘console’

[nodejs] raw_input in Node.js

November 7, 2015 Leave a comment

Problem
How to read in Node.js from the console? For instance, how to rewrite the following Python script?

n1 = int(raw_input("1st number: "))
n2 = int(raw_input("2nd number: "))

print "The sum is:", n1+n2

Solution

#!/usr/bin/env node

"use strict";

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function processNums(n1, n2) {
    n1 = Number(n1);
    n2 = Number(n2);
    console.log("Their sum: " + (n1 + n2));
}

function start() {
    rl.question('1st number: ', function (x) {
        rl.question('2nd number: ', function (y) {
            rl.close();

            processNums(x, y);
        });
    });
}

function main() {
    start();
}

main();

Tip from here.

Advertisements
Categories: nodejs Tags: , ,