const termios = require("node-termios"); module.exports = {}; let inputBuffer = ""; let initialised = false, haveEOF = false; let waitQueue = []; function stdinDataListener(data) { data = data.toString(); inputBuffer += data; if (waitQueue.length == 0) return; const idx = inputBuffer.indexOf("\n"); if (idx == -1) return; waitQueue.shift()[0](inputBuffer.slice(0, idx)); inputBuffer = inputBuffer.slice(idx + 1); } function stdinEndListener() { haveEOF = true; for (const [resolve, reject] of waitQueue) { reject("End-of-file reached"); } waitQueue = []; } function init() { process.stdin.on("data", stdinDataListener); process.stdin.on("end", stdinEndListener); initialised = true; } module.exports.init = init; function end() { process.stdin.removeListener("data", stdinDataListener); process.stdin.removeListener("end", stdinEndListener); process.stdin.end(); } module.exports.end = end; function getline() { return new Promise((resolve, reject) => { if (haveEOF) { reject("End-of-file reached"); return; } const idx = inputBuffer.indexOf("\n"); if (idx != -1) { const line = inputBuffer.slice(0, idx); inputBuffer = inputBuffer.slice(idx + 1); resolve(line); } else { waitQueue.push([resolve, reject]); } }); } module.exports.getline = getline; function getpassword() { return new Promise(async (resolve, reject) => { const origtty = new termios.Termios(0); const tty = new termios.Termios(0); tty.c_lflag &= ~(termios.native.ALL_SYMBOLS.ECHO | termios.native.ALL_SYMBOLS.ECHONL); tty.writeTo(0); let handler; try { const line = await getline(); handler = () => resolve(line); } catch (e) { handler = () => reject(e); } console.log(); // ~ECHO eats newline origtty.writeTo(0); handler(); }); } module.exports.getpassword = getpassword; async function prompt(str) { process.stdout.write(str); return await getline(); } module.exports.prompt = prompt; async function promptPassword(str) { process.stdout.write(str); return await getpassword(); } module.exports.promptPassword = promptPassword; function eof() { return haveEOF; } module.exports.eof = eof;