Nodejs a simple command-line input-output REPL interface with recursive implementation of chained calls to asynchronous operations

Source: Internet
Author: User

Repl--read-eval-print-loop.00. The necessary conditions for a good programming language

REPL is not a big thing, simply speaking is a program from the command line, read terminal input, processing, printing results, so loop. This is the basis for a more comprehensive programming language.

Just started to contact Nodejs, thought is a service-side JS, but after a period of learning to feel its strong and charm. If Java is an old-fashioned player who likes to behave in a programming game, JavaScript is a graceful and unrestrained player. Just started to transform asynchronous programming is very unaccustomed, slowly understand, asynchronous programming, is a kind of thinking.

01. The gourd cannot be drawn

A command line read input, processing program, Java can write a while loop to use scanner to ReadLine, but if imitate Java with JS is a bit of trouble,

var RL = require (' ReadLine '); (true) {    rl.on (' line ', function (data) {        //to deal data    });}

This is obviously not a good drop, but the ape accustomed to the synchronous programming might do so, JavaScript async means a non-blocking design, not because of the user input blocking the next loop. So to tell JavaScript to do the next read (callback) after this one processing, the problem is that the infamous callback hell is likely to happen.

10. How to properly draw the scoop, but also to look comfortable

Solution 1: Use the async,co,q, promise, and so on mechanisms to synchronize

Solution 2: For a REPL program, the logic is simple, if you implement a chained invocation of the interface is good, like this:

Read ("Var1", function (data) {}). Read ("Var2", function (data) {}) ...

Writing native code is easier to debug than using open source libraries, and killing chickens with sledgehammer, not trouble with the module of CO, q this then () chain call passable, want to do what directly. xx (). XX () more intuitive.

11. Silver Bullet

The simple thing behind it must be to conceal its true complexity in a more complex or sophisticated way.

Repl.js

var readline = require (' ReadLine ');                                  Very handy node comes with library var RL = NULL;                         Singletonvar questions = [];                               Processing queue var cursor = 0; Cursor function dealquestions (_self) {////recursive processing queue for read requests if (cursor >= questions.length) {cursor = 0;question        s = [];        Rl.close ();        RL = NULL;    return _self;        } rl.question (Questions[cursor].question, function (data) {questions[cursor].deal (data);        ++cursor;                      Dealquestions (); Read processing completed callback});            var easyrepl = function () {if (RL = = NULL) {//Initialize module RL = Readline.createinterface ({    Input:process.stdin, output:process.stdout}); } return this;};/ * * @description: A liner API to get console input * @param: question to ask, function to deal answer * */easyrepl.pro             Totype.question = function (question,dealanswer) {easyrepl ();                        Rl.prompt ();                            var _self = this;  Save this pointer Questions.push ({question:question,deal:dealanswer});    Join the processing queue if (questions.length = = 1) {dealquestions (_self);                                   } return this; Key to implementing chained calls: Returns This};exports. Repl_mode = EASYREPL;

Test code: Test.js

var Easyrepl = require ("./repl"). Repl_mode;var test = new Easyrepl ();/* comment following codes to test command Mode */test.question ("Input name:", Functi On (data) {    console.log ("Get name:" +data);}). Question ("Input Password:", function (data) {    console.log ("Get Password:" +data);}). Question ("Input Email:", function (data) {    console.log ("Get Email:" +data);});

Output:

This is a primer, Nodejs can do too much, in addition to do a parse input command program, code than this, but not enough essence, or not put.

Nodejs a simple command-line input-output REPL interface with recursive implementation of chained calls to asynchronous operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.