是否可以使用 readline 從控制台串流輸入? (Node.js、JS)
P粉868586032
P粉868586032 2024-02-21 17:53:14
0
1
425

我有一個條件數組 ARR,我想在一行中向其寫入值

我嘗試這樣做

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('')

但是當我這樣做時,我得到了逐行輸入:

Enter Values:
    1
    A
    2
    B

我需要:

Enter Values: 1 A 2 B

P粉868586032
P粉868586032

全部回覆(1)
P粉457445858

readline 用換行符號分隔輸入流,但您想用空格分隔它。下面的轉換流可以實現這一點。注意,它是與 for wait (...) {} 而不是 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);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!