【发布时间】:2018-09-09 22:30:45
【问题描述】:
我还是 nodeJs 的新手,我正在尝试创建一个输入流,但是一旦我通过调用 node fileName 在终端中启动应用程序,我的代码就无法正常工作。
我的输入格式是这样的:
- N the number of queries.
- second line represent a string containing two words separated by a space.
- N lines of a string containing two words separated by a space.
由于某种原因,终端没有显示任何东西。
这是我的代码:
'use strict';
const fs = require('fs');
var n = 0;
var position = '';
var destination = '';
var array = [];
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const s = parseInt(readLine(), 10);
const input= readLine().split(' ');
position = input[0] ;
destination = input[1];
console.log('our number is',s, 'and our position and destination:', position, destination);
ws.end();
}
【问题讨论】:
-
您的代码大部分都有效。您正在从标准输入读取,这会导致终端锁定到 EOF。如果您正在创建过滤程序,这很好。如果没有,您需要打开一个不同的 ReadableStream。
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);这也会引发错误。当您收到数据并使用 shell io 重定向输出到文件时,您应该只写入标准输出。
标签: javascript node.js input