Search code examples
javascriptnpmuser-inputprompt

Returning from prompt.get


I'm currently using the prompt package in Node to get user input on the command line, however, I would like to return a variable from prompt.get - how would I store the return variable/where can I access it from? I'm relatively new to Node.

const prompt = require('prompt');

prompt.start();
prompt.get(['num'], function (err: any, result: any) {
    if (err) { return Error(err); }
    if(result.num > 0) {
        return "Positive";
    }
    else {
        return "Negative";
    }
});

Cheers!


Solution

  • You could initialize the variable outside the callback, and then set the variable inside of the callback:

    let value;
    
    prompt.get(['num'], function (err: any, result: any) {
        if (err) { return Error(err); }
    
        value = result > 0 ? "Positive" : "Negative";
    });
    

    But the problem is the value will be empty until it's done, so if you try to call it right after, it will be empty.

    let value;
    
    prompt.get(['num'], function (err: any, result: any) {
        if (err) { return Error(err); }
    
        value = result > 0 ? "Positive" : "Negative";
    });
    
    console.log(value); // => undefined
    

    The package also supports promises though, so you can just use await, as shown on their readme:

    (async () => {
        const { num } = await prompt.get(['num']);
    })();
    

    You should notice the anonymous self executing async function, that's because await only works inside of async functions (technically not needed after node v15 & while using modules).