I'm rather new to javascript and the async programming outside of multithreading. Lately I've sort of bumped into an issue with readline as I'm trying to break it into a function to be able use it more like a normal input-function. The test-program consists of two files, a main-file and the module which I'm trying to get to work.
Main file:
"use strict";
const readline = require("readline");
const terInput = require("./modules/terInput");
(async function main() {
let value;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
value = await terInput(rl, "Write value: ");
rl.close();
}());
Module file:
"use strict";
async function terInput(rl, question) {
let retValue;
rl.question(question, async function (value) {
retValue = value;
});
return retValue;
}
module.exports = terInput;
What I want to achieve with this little code is to simplify the use of question for my own self. Thing is if I try to run this program, I get Write value:
as an answer and no input, which isn't very thrilling. I've tried to move the return value into different places and so on, but it doesn't help my case. Tried to place rl.close()
inside of the function instead as I figured maybe the interface got closed before the function. That however doesn't help either. I'm very new to the javascript mindset, coming from a C++ background it's a rather tricky one to wrap my head around. If anyone has any ideas around the issue I'd be very thankful. I've tried to find others having the same issue with it, but I haven't gotten anywhere in that search yet.
Thanks in advance
Edit
After further testing I've found that the program doesn't wait on the function even if await is called. I tested this through again putting rl.close()
into the question-function. This looks something like this:
"use strict";
async function terInput(rl, question) {
let rValue;
rl.question(question, async function(value) {
rValue = value;
rl.close();
});
return rValue;
}
module.exports = terInput;
This code does somewhat work, using this and no output after this function-call in the main-file will give you input. This means that code something in the style of this:
(async function main() {
let value;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
value = await terInput(rl, "Write value: ");
}());
Will ask for input, however code like this:
(async function main() {
let value;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
value = await terInput(rl, "Write value: ");
console.log(value);
}());
Will not work, which is rather confusing to me. It will instead give you Write value: undefined
where undefined
comes from the console.log()
(hinting at the question-function not printing out a "\n" into the output-buffer either). There's probably some javascript magic which will fix this, if anyone has any interesting thoughts around it, I'd be glad to hear it.