[英]Detect pasted input with Readline NodeJs
我們正在使用 Node JS 和readline
庫。 我們正在嘗試檢測所有按鍵以模擬終端。 但是我們希望將復制粘貼輸入視為單個字符串。 我們如何使用 readline 庫來做到這一點。 這是我們的代碼片段:
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (_, key) => {
this.logger.debug(JSON.stringify(key));
terminal.writeString(key.sequence)
});
您可以通過使用超時來實現此行為。 將鍵輸入添加到列表中,並在一定時間后將該列表傳遞給您的輸入處理程序。
下面的代碼應該解釋自己。
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
// increase value for slower / older devices, 3 is enough for me
const maxInputDelay = 3;
// internal values
let keyInput = [];
let timeoutId = -1;
process.stdin.on('keypress', (_, key) => {
// add key to input array
keyInput.push(key /*.sequence*/);
// reset the timer for each new input received
if (timeoutId !== -1) clearTimeout(timeoutId);
// send the input to a function after a certain amount of time has passed
timeoutId = setTimeout(() => {
// handle input and clear array
handleInput(keyInput);
keyInput = [];
}, maxInputDelay)
});
// handle input
function handleInput(keys) {
console.log("input received:", keys, `isPaste = ${keys.length > 1}`)
// your code goes here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.