【问题标题】:handling nodeJs input from console?处理来自控制台的nodeJs输入?
【发布时间】: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


【解决方案1】:

您可以通过允许 readline 缓冲输入来简化整个事情:

'use strict';

const readline = require('readline');

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

rl.on('line', line => {
    rl.write(
        line.replace(/\s*$/, '')
    );
});

【讨论】:

  • 只是想问一下缓冲输入是什么意思??
  • 好问题!在您的原始代码中,在data 上,您是 += 字符串的块。这称为缓冲,当您将一块一块地放入更大的存储中时——想想视频流。 Readline 会为您解决这个问题,大大简化了代码。流的内部缓冲区可能很小,一次从源中获取少量数据,但少量数据没有意义,因此您将其构建为更大的部分,即缓冲。在这种情况下,我们正在执行行缓冲 io。
  • 要驱动这个家,想象一个大视频,它不太可能适合内存,而现实是,你不需要(因为用户一次只能看到一个视频帧) .如果播放速度快于获取数据,则视频冻结,必须等待来自流源的更多数据---缓冲。
猜你喜欢
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多