Tuesday 2 October 2018

node.js: readline: Building simple command line interface

Below program is simple command line interface, that echos the message given by user. You should type ‘exit’ to exit from the command line tool.

HelloWorld.js
var readline = require('readline');

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

rl.prompt();

rl.on('line', (line) => {
    switch (line.trim()) {
        case 'exit':
            rl.close();
        default:
            console.log(`'${line.trim()}'`);
            break;
    }
    rl.prompt();
}).on('close', () => {
    console.log('Close Event received, Have a good day!!!!!');
    process.exit(0);
});


Sample Output
#> Hi
'Hi'
#> Hello, How are you
'Hello, How are you'
#> Good Morning!!!!!
'Good Morning!!!!!'
#> exit
Close Event received, Have a good day!!!!!


Previous                                                 Next                                                 Home

No comments:

Post a Comment