问题描述
如果我想从 C 中的输入流中读取,我写 scanf
。, NodeJS中是否有等效方法做同样的事情?
If I want to read from the input stream in C I write scanf
., Is there equivalent method in NodeJS to do the same?
例如,这里的代码是 C
int n,
m,
i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &m);
............
}
这是我从Node开始的地方... TODO 表示我被困的地方:
Here's where I'm starting from in Node... TODO indicates where I'm stuck:
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) {
var n = +input;
for (var i = 0; i < n; i++) {
// TODO
}
});
推荐答案
对于初学者,请致电 scanf
和NodeJS中可读流的数据
事件不等效。在NodeJS示例中,您将需要解析您收到的输入的块。
For starters, calling scanf
and the data
event for a readable stream in NodeJS are not equivalent. In the NodeJS example, you will need to parse the chunk of the input you've received.
您可以通过替换以下内容来检查这些块的发送方式。你的on方法很简单:
You can examine how these chunks are sent to you by replacing the body of your on method with a simple:
process.stdout.write('onData: ' + input + '\n');
鉴于如何输入
然后包含你的数据你我需要使用一些方法来提取感兴趣的字符串,然后使用 parseInt
。假设你的问题很简单,假设每个输入为1个整数
:
Given how input
then contains your data you'll need to use some method to extract the string of interest and then use parseInt
. Perhaps a naive approach to your problem, assuming 1 integer per input
:
var n = 0;
var m = 0;
var state = 0;
process.stdin.on('data', function (input) {
switch (state)
{
case 0:
// we're reading 'n'
n = parseInt(input.trim(), 10);
state++;
break;
default:
// we're reading 'm'
m = parseInt(input.trim(), 10);
if (state++ == n)
{
// we've read every 'm'
process.exit();
}
break;
}
});
我不是这种将数据传递到NodeJS事件循环的非常大的粉丝,你应改为查看命令行参数,配置/输入文件或其他方法。
I'm not a terribly large fan of this means of getting data to your NodeJS event loop, you should instead look to command line arguments, configuration/input files, or some other means.
这篇关于nodejs中的C scanf等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!