@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
85 lines (75 loc) • 2.3 kB
JavaScript
const readline = require('node:readline')
const { Writable } = require('node:stream')
async function ask4([...args], { redacted = false } = {}) {
var mutableStdout = new Writable({
write: function (chunk, encoding, callback) {
if (!redacted)
process.stdout.write(chunk, encoding);
callback();
}
});
// If not in interactive mode, read all input at once.
if (!process.stdin.isTTY) {
const data = await new Promise(resolve => {
let result = ''
process.stdin.on('data', chunk => result += chunk)
process.stdin.on('end', () => resolve(result))
})
return data.split(/\r?\n/).slice(0, args.length)
}
const answers = []
const rl = readline.createInterface({
input: process.stdin,
output: mutableStdout,
terminal: true
})
const askQuestion = question =>
new Promise(resolve => {
if (redacted && process.stdin.isTTY) {
// Set raw mode to intercept keystrokes
process.stdin.setRawMode(true)
process.stdout.write(question)
let answer = ''
const onData = (char) => {
const byte = char.toString()
// Enter key
if (byte === '\n' || byte === '\r') {
process.stdin.setRawMode(false)
process.stdin.removeListener('data', onData)
process.stdout.write('\n')
answers.push(answer)
resolve()
}
// Backspace/Delete
else if (byte === '\b' || byte === '\x7f') {
if (answer.length > 0) {
answer = answer.slice(0, -1)
process.stdout.write('\b \b')
}
}
// Ctrl+C
else if (byte === '\x03') {
process.stdin.setRawMode(false)
process.exit()
}
// Regular character
else if (byte >= ' ' || byte === '\t') {
answer += byte
process.stdout.write('*')
}
}
process.stdin.on('data', onData)
} else {
rl.question(question, answer => {
answers.push(answer)
resolve()
})
}
})
for (const question of args) {
await askQuestion(question)
}
rl.close()
return args.length == 1 ? answers[0] : answers
}
module.exports = { ask4 }