A
A
Annalana2021-04-24 09:25:35
Node.js
Annalana, 2021-04-24 09:25:35

It is not possible to wait for a response from the console in Node, how to implement it?

Good afternoon!
I am writing an educational website. I ran into a problem when trying to make a script for data management. This one should read input from the console and send it to MongoDB. At the moment, the code runs, but instead of waiting for a response, it immediately issues the following prompt. Tried to use onmessage and use message as the first parameter for on - didn't work.
Is it possible to do something so that it waits for the event of sending a string to the console? It is the part of the input from the console that is of interest, there may be some errors further, since it has not been tested, this is no longer important - I will fix it :)
Thank you!

const mongoose = require("mongoose");
mongoose.connect("mongodb://***", {useUnifiedTopology: true, useNewUrlParser: true})
const db = mongoose.connection;
const MODELS = require("../bd_config/Models.js");
let readline = require('readline'); 
let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false,
    prompt: '>'
});
let test = true;
function prompt_await(text){
    console.log(text);
    rl.prompt();
  
    rl.on(`line`, (input) => {
        if(input != ""){            
            rl.close();
            return input;    
        }else{
            process.exit();
            return NaN
        }
       });
};
let c_id, c_name, category;

while (test = true) {
    c_id = prompt_await("Введите ID категории, на английском");
    c_name = prompt_await("Введите имя категории для пользователей (на русском)");  
    category = {category_name: c_id, category_name_for_user: c_name};
    if (c_id = NaN && c_name != Nan){
        test = false;
    }else{
        MODELS.Category.create(category).then(
            function(result){
                console.log(result);
                },
            function(error){
            console.log(error)
            });
    }   
}
process.exit(1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dispache, 2021-04-24
@Annalana

Convenient wrapper over readline - https://www.npmjs.com/package/console-read-write ,
allowing you to use async/await

const io = require('console-read-write'); 
io.write('Введите ИД категории');
let x = await io.read(); // тут ожидаемый ввод в консоль
console.log(x);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question