Node.js中的用户输入

vam*_*afa 15 javascript node.js

我正在编写一个程序,它将创建一个数字数组,并将每个数组的内容加倍,并将结果存储为键/值对.早些时候,我对阵列进行了硬编码,所以一切都很好.

现在,我已经改变了一些逻辑,我想从用户那里获取输入,然后将值存储在一个数组中.

我的问题是我无法弄明白,如何使用node.js来做到这一点.我已经使用npm安装提示安装了提示模块,并且已经完成了文档,但没有任何工作.

我知道我在这里犯了一个小错误.

这是我的代码:

//Javascript program to read the content of array of numbers
//Double each element
//Storing the value in an object as key/value pair.

//var Num=[2,10,30,50,100]; //Array initialization

var Num = new Array();
var i;
var obj = {}; //Object initialization

function my_arr(N) { return N;} //Reads the contents of array


function doubling(N_doubled) //Doubles the content of array
{
   doubled_number = my_arr(N_doubled);   
   return doubled_number * 2;
}   

//outside function call
var prompt = require('prompt');

prompt.start();

while(i!== "QUIT")
{
    i = require('prompt');
    Num.push(i);
}
console.log(Num);

for(var i=0; i< Num.length; i++)
 {
    var original_value = my_arr(Num[i]); //storing the original values of array
    var doubled_value = doubling(Num[i]); //storing the content multiplied by two
    obj[original_value] = doubled_value; //object mapping
}

console.log(obj); //printing the final result as key/value pair
Run Code Online (Sandbox Code Playgroud)

请帮助我,谢谢.

Ric*_*ick 37

对于那些不想导入另一个模块的人,可以使用标准的nodejs进程.

function prompt(question, callback) {
    var stdin = process.stdin,
        stdout = process.stdout;

    stdin.resume();
    stdout.write(question);

    stdin.once('data', function (data) {
        callback(data.toString().trim());
    });
}
Run Code Online (Sandbox Code Playgroud)

用例

prompt('Whats your name?', function (input) {
    console.log(input);
    process.exit();
});
Run Code Online (Sandbox Code Playgroud)


jos*_*736 7

提示是异步的,因此您必须异步使用它.

var prompt = require('prompt')
    , arr = [];

function getAnother() {
    prompt.get('number', function(err, result) {
        if (err) done();
        else {
            arr.push(parseInt(result.number, 10));
            getAnother();
        }
    })
}

function done() {
    console.log(arr);
}


prompt.start();
getAnother();
Run Code Online (Sandbox Code Playgroud)

这将推送数字,arr直到你按Ctrl+ C,此时done将被调用.


Gov*_*Rai 5

带有ES6 Promises的现代Node.js示例,没有第三方库。

Rick提供了一个很好的起点,但是这是一个更完整的示例,说明了一个又一个提示性问题如何在以后又可以引用这些答案。由于读/写是异步的,因此Promise /回调是在JavaScript中编写此类流程的唯一方法。

const { stdin, stdout } = process;

function prompt(question) {
  return new Promise((resolve, reject) => {
    stdin.resume();
    stdout.write(question);

    stdin.on('data', data => resolve(data.toString().trim()));
    stdin.on('error', err => reject(err));
  });
}


async function main() {
  try {
    const name = await prompt("What's your name? ")
    const age = await prompt("What's your age? ");
    const email = await prompt("What's your email address? ");
    const user = { name, age, email };
    console.log(user);
    stdin.pause();
  } catch(error) {
    console.log("There's an error!");
    console.log(error);
  }
  process.exit();
}

main();
Run Code Online (Sandbox Code Playgroud)

  • 确保你调用 `stdin.pause()` 或节点将保持该流处于活动状态... (3认同)
  • 啊,是的,我已经在示例中进行了更新。谢谢! (2认同)

Sha*_*hay 5

Node.js 实现了一个简单的 readline 模块,它异步执行:

https://nodejs.org/api/readline.html

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});
Run Code Online (Sandbox Code Playgroud)