Home  >  Q&A  >  body text

Is it possible to use readline to stream input from the console? (Node.js, JS)

I have a conditional array ARR and I want to write values ​​to it in one row

I try to do this

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'process';

const rl = readline.createInterface({input, output})

let arr =[]
console.log('Enter Values: ')
for (let i = 0; i < 5; i++) {
     arr[i] = await rl.question('')

But when I do this, I get line-by-line input:

Enter Values:
    1
    A
    2
    B

I need to:

Enter Values: 1 A 2 B

P粉868586032P粉868586032263 days ago445

reply all(1)I'll reply

  • P粉457445858

    P粉4574458582024-02-22 12:09:45

    readline Separate the input stream with newlines, but you want to separate it with spaces. The following transformation flow achieves this. Note that this is used with for wait (...) {} instead of for (...) { wait }.

    var input = new stream.Transform({
      readableObjectMode: true,
      transform(chunk, encoding, callback) {
        this.buffer = this.buffer ?
          Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length) :
          chunk;
        while (true) {
          var offset = this.buffer.indexOf(" ");
          if (offset === -1) break;
          this.push(this.buffer.toString("utf8", 0, offset));
          while (this.buffer[offset + 1] === 0x20) offset++;
          this.buffer = this.buffer.slice(offset + 1);
        }
        callback();
      }
    });
    console.log('Enter Values: ');
    process.stdin.pipe(input);
    let arr = [];
    let i = 0;
    for await (var number of input) {
      arr[i] = number;
      i++;
      if (i >= 5) break;
    }
    console.log(arr);
    

    reply
    0
  • Cancelreply