Readline node js iteration with 1 step - node.js

I want to make a function that gets the number from the console and iterates it with 1 step till the 100 number and stop. Please help to solve the problem! Thanks!
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ask = msg => new Promise(resolve =>
rl.question(msg, response => resolve(response))
);
const simpleInterest = (min) => {
for(min; min < 100; min +1) {
return min
};
};
const main = async () => {
const min = await ask("min number: ");
console.log(simpleInterest(min));
rl.close();
};
main();

Related

Readline node.js undefined Math.floor function error

I want to build node js console asking tool.
Please help, I have an undefined error in the console. What is the problem?
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ask = msg => new Promise(resolve =>
rl.question(msg, response => resolve(response))
);
const simpleInterest = (min, max) => {
const math = Math.floor(Math.random() * (max - min + 1)) + min;
};
const main = async () => {
const min = await ask("min numer: ");
const max = await ask("max number: ");
console.log(simpleInterest(+min, +max));
rl.close();
};
main();
The simpleInterest function is not returning anything. Try this:
const simpleInterest = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};

NodeJS reading files and putting lines as function arguments

How can I put data from an external txt file to function argument? I get undefined because reading files is asynchronous and the values which I give to the functions are undefined. How can I make it work? Each line is one variable.
let numberOfElephants;
let massOfElephants;
let elephantsOrderGiven;
let proposedOrder;
const readFile = () => {
return new Promise((resolve, reject) => {
const lineArray = [];
const readInterface = readline.createInterface({
input: fs.createReadStream("./slo1.in"),
output: process.stdout,
terminal: false,
});
readInterface
.on("line", (line) => {
lineArray.push(line);
})
.on("close", () => {
resolve(lineArray);
});
});
};
async function readAsync() {
const res = await readFile();
numberOfElephants= res[0],
massOfElephants= res[1],
elephantsOrderGiven= res[2],
proposedOrder= res[3],
}
console.log("read");
readAsync();
const sortElephants = (
numberOfElephants,
massOfElephants,
elephantsOrder,
directorsOrder
) => {}
sortElephants(
numberOfElephants,
massOfElephants,
elephantsOrderGiven,
proposedOrder
)

Wait for user input every time and continue in the loop. Using node js

I need a node js function that goes through two arrays and waits for user input every time and then continues to loop.
let array = **SOME_ARRAY**;
let array_2 = **SOME_ARRAY**;
for (let i in array) {
for (let j in array_2) {
process.stdin.on('data', data => {
data = data.toString();
data = data.replaceAll('\r', '').replaceAll('\n', '');
console.log(data, array[i], array_2[j]);
});
}
}
You could use readline.question with async-await:
const readline = require('readline');
function readInput() {
const interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => interface.question("Please provide next input: ", answer => {
interface.close();
resolve(answer);
}))
}
(async () => {
const array = [1, 2];
const array2 = [4, 5];
for (const a of array) {
for (const b of array2) {
const data = await readInput();
// Do something with your data...
console.log(data, a, b);
}
}
})();

Asking multiple questions with readline nodejs

I am attempting to get both username and password from the CLI in a puppeteer project. I get it to ask one question and can use the value just fine, but when I do the second it just freezes on the input. It is almost like it is not actually closing and returning. I cannot seem to figure out what I am missing. I tried to declare the interface in the question method and then destroy it when close is called, but that did not work. I feel like I am close, but I cannot figure out what I am missing.
const login = require('../common/login.js');
userId = await login.getUserId();
console.log(userId) //works
password = await login.getPassword();
console.log(password) //does not work
login.js
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
var methods = {};
const question = (promptText) => {
let response;
readline.setPrompt(promptText)
readline.prompt();
return new Promise((resolve, reject) => {
readline.on('line', (userInput) => {
console.log('hi');
response = userInput;
readline.close();
});
readline.on('close', () => {
console.log('bye');
resolve(response);
})
})
};
methods.getUserId = async() => {
let username = question("Username: ");
return username;
}
methods.getPassword = async() => {
let password = question("Password: ");
console.log(password);
return password;
}
module.exports = methods;
The readline.close() will close the streams. The below code works for me
const rli = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function input(prompt) {
return new Promise((callbackFn, errorFn) => {
rli.question(prompt, (uinput)=> {
callbackFn(uinput);
}, ()=> {
errorFn();
});
});
}
const main = async () => {
amt = await input("Enter the amount to check: ");
doSomething(amt);
uname = await input("Enter your name: ");
doSomethingElse(uname);
rli.close();
};
main();

Node.js readline inside of promises

I'm trying to use the node.js package readline to get user input on the command line, and I want to pipe the entered input through promises. However, the input never gets through the then chain. I think the problem could come from the fact that the promises are fulfilled in the callback method, but I don't know how to solve that problem.
An example of this problem looks like this:
import rlp = require('readline');
const rl = rlp.createInterface({
input: process.stdin,
output: process.stdout
});
let prom = new Promise(resolve => {
rl.question('Enter input: ', input => rl.close() && resolve(input));
});
prom
.then(result => { console.log(result); return prom; })
.then(result => { console.log(result); return prom; })
.then(result => console.log(result));
If run in node.js, the question will appear once, after input has been entered the program just stops. I want it to wait until the first input has been entered, then it should print this input and ask for the next input.
Thanks in advance!
Once your promise is resolved, there's no use of waiting for that again. I also moved the rl.close() call to the end, as it's needed to be called only once.
const rlp = require('readline');
const rl = rlp.createInterface({
input: process.stdin,
output: process.stdout
});
function ask() {
return new Promise(resolve => {
rl.question('Enter input: ', input => resolve(input));
});
}
ask()
.then(result => { console.log(result); return ask(); })
.then(result => { console.log(result); return ask(); })
.then(result => { console.log(result); rl.close() });
Here's an answer from this question here for which I deserve no credit.
// Function
function Ask(query) {
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise(resolve => readline.question(query, ans => {
readline.close();
resolve(ans);
}))
}
// example useage
async function main() {
var name = await Ask("whats you name")
console.log(`nice to meet you ${name}`)
var age = await Ask("How old are you?")
console.log(`Wow what a fantastic age, imagine just being ${age}`)
}
main()
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (query) => new Promise((resolve) => rl.question(query, resolve));
ask('A: ').then(async (a) => {
const b = await ask('B: ');
const c = await ask('B: ');
console.log(a, b, c);
rl.close();
});
rl.on('close', () => process.exit(0));
Node.js 17 is here with new promise-based APIs for readline module:
import * as readline from 'node:readline/promises'
import { stdin as input, stdout as output } from 'process'
const rl = readline.createInterface({input, output})
const answer = await rl.question('What do you think of Node.js? ')
console.log(`Thank you for your valuable feedback: ${answer}`)
rl.close()
https://nodejs.org/api/readline.html#readline
node prompt.mjs
import { createInterface as createQuestionInterface } from 'readline';
const rl = createQuestionInterface({
input: process.stdin,
output: process.stdout
});
function questionLine(multiline, resolve, i, input, rl) {
if (!multiline) {
resolve(i);
} else {
if (input && !i) {
resolve(input);
} else {
return input + i + "\r\n";
}
}
return input;
}
function promptMultiLine(questionText) { // This is async by returning promise
return prompt(questionText, true);
}
async function prompt(questionText, multiline = false) {
return await (new Promise((resolve, reject) => {
let input = '';
rl.question(`${questionText}: `, (i) => {
input = questionLine(multiline, resolve, i, input, rl);
});
rl.on('line', (i) => {
input = questionLine(multiline, resolve, i, input, rl);
});
}));
}
async function run() {
const question = prompt("please enter response [enter to complete]");
console.log(question);
const questionMultiLine = promptMultiLine("please enter response [enter text and enter twice]");
console.log(questionMultiLine);
}
run();

Resources