I am using the prompt module, node version 12.4.0
I am wondering if its possible to push a string to the 'input field' of a prompt.get()
The following script displays a (double) "prompt: "
After 5 seconds, it inserts the text "This is a test"
When an enter command is given, the string is not recognized as input.
It isn't possible to edit the string before pressing enter either.
(type anything before 5 sec and press enter, and the input WILL display)
End-goal: to have commands send to prompt from external source, but give the end user the ability to modify the commands before entering.
I tried process.stdout.write, process.stdin.write
I also tried to replace process.std*.write with prompt.std*.write
The answer might be os-specific, but I have tried this code both under Win10 x64 as well as Linux
const prompt = require("prompt");
function myFunc() {
process.stdin.write("This is a test");
}
setTimeout(myFunc, 5000);
prompt.get({
properties: {
test: {
description: "prompt"
}
}
}, (err, result)=> {
console.log("input: "+ result.test);
});
actual result:
~/Nodejs/temp$ node index.js
prompt: prompt: This is a test
input:
~/Nodejs/temp$
desired result:
~/Nodejs/temp$ node index.js
prompt: prompt: This is a test
input: This is a test
~/Nodejs/temp$
After digging into how the prompt module works, I 'solved' this myself.
prompt uses readline behind the curtains, and readline has a .write function that does what I need, send editable text to the prompt.
prompt itself does not extend this function, and since it hasnt been maintained for 3 years, I switched to readline instead.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'prompt> '
});
rl.prompt();
rl.on('line', (line) => {
console.log(line);
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
// simulate external input, and write to prompt>
function myFunc() {
rl.write("This is a test");
}
setTimeout(myFunc, 5000);