簡體   English   中英

如何在 nodejs 中向 forawait readline 添加問題?

[英]How can I add a question to forawait readline in nodejs?

我正在瀏覽 nodejs 文檔以獲得某些功能,我發現了一個forawait功能,但我無法對其提出問題。

這是文檔示例:

async function processLineByLine() {
  const rl = readline.createInterface({
    // ...
  });

  for await (const line of rl) {
    // Each line in the readline input will be successively available here as
    // `line`.
  }
}

這是我的嘗試:

const readline = require('readline');
const { promisify } = require('util');

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

const promptUserCLI = (q, exitAnswers = [], callback) => {
  rl.question(q, answer => {
    if (exitAnswers.includes(answer)) {
      rl.close();
    } else {
      callback(null, answer);
    }
  });
};


const promptPromise = promisify(promptUserCLI)

// this data must have some relation to the question.
// --  and therefore I have to iterate over it somehow in a clean way.
const data = require('./file.json');

async function processLineByLine(callback) {
  rl[Symbol.asyncIterator] = async function* () {
    let index = 0
    while (true) {
      const item = data[index]

      const answer = await promptPromise(`Make '${item.line}' [ [y]es/no/all/exit ]`, ['exit', 'quite'])

      index += 1

      return {
        async * next() {
          yield { answer, item, index }
        }
      }
    }
  }

  for await (const line of rl) {
    let isClosed = false
    const close = () => isClosed = true
    callback(line, close)

    if (isClosed) break
  }
}

// uncomment for testing: this should log(line, [Function: close])
// -- Note: line should have: { answer, item, index }
// processLineByLine(console.log)


// my best shot was using raw generator, yet, this doesn't break out the loop if I intended to use `break` keyword
async function* gen() {
  let index = 0
  while (true) {
    const item = data[index]

    const answer = await promptPromise(`Make '${item.line}' [ [y]es/no/all/exit ]`, ['exit', 'quite'])

    index += 1

    yield { answer, item, index }
  }
}

// this is a perfect example of it "almost" working as I need
;; (async () => {
  try {
    for await (const item of gen()) {
      console.log('item', item)

      // the break here won't break, if this get solved I'm good, that's all I need.
      break
    }
  } catch (e) {
    console.log(e)
  }
})()

數據外觀的一個小快照。

[
  {
    "line": "Lorem ipsum verties sit amet, consectetur adipiscing elit.",
    "replacements": [],
    "indices": [
      0
    ]
  },
  {
    "line": "Vivamus tincidunt verties sit amet libero laoreet aliquet.",
    "replacements": [],
    "indices": [
      0
    ]
  },
  {
    "line": "Nulla sodales ipsum verties lorem elementum, vitae porttitor nisi pellentesque.",
    "replacements": [],
    "indices": [
      0
    ]
  },
  {
    "line": "Nullam verties dui eget nulla facilisis porttitor.",
    "replacements": [],
    "indices": [
      0
    ]
  }
]

Ps:我不知道如何向我的for await readline 生成器添加問題•

你有想法嗎?

轉載: https ://replit.com/@meno101/temp#index.js 來源: https ://nodejs.org/api/readline.html#rlsymbolasynciterator

謝謝大家的合作,如果你找到這個問題的任何答案,請隨時發布,否則我認為在一個簡單的任務上浪費太多時間是不值得的。

好奇的? 我刪除了 forawait 部分,並在 IIFE 部分中調用gen生成器后在循環后添加了一個rl.close() ,如果我爆發了,我會讓它為我做這項工作。

;; (async () => {
  try {
    for await (const item of gen()) {
      console.log('item', item)

      // the break here won't break, if this get solved I'm good, that's all I need.
      break
    }
    rl.close()
  } catch (e) {
    console.log(e)
  }
})()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM