Tips for closing process.stdin.on and then reopening it later

I've been facing a challenge with an exercise. In this exercise, the client will input a specific integer x, followed by x other y values separated by spaces. The output should be the sum of each y value, also separated by spaces.

For example:

Input: 4            |  Input: 5
       21 35 55 66  |         333 53 99 12 55
Output: 3 8 10 12    |  Output: 9 8 18 3 10

and so forth...

While I have grasped the main concept, my struggle lies in understanding the process.stdin.on('data', function() ...) part of the code.

I couldn't find many helpful videos or explanations on this topic.

After watching two brief explanatory videos, here is what I attempted:

let number = null;

let numOrder = [];


function clientsnum() {
  process.stdout.write("Enter number: ");

  process.stdin.on("data", function (data) {
    number = parseInt(data.toString().trim());
    process.stdin.pause();
  });

  process.stdin.on("pause", function () {
    console.log("Paused");
    process.stdout.write(`${numOrder} ${number}` + "\n"); //for debugging
    order();
  });
}

function order() {
  console.log("got here");                   //for debugging
  process.stdout.write("numberOrder: ");
  process.stdin.resume();
  process.stdin.on("data", function (data) {
    if (numOrder.length < number) {
      numOrder.push(parseInt(data.toString().trim()));
    } else {
      process.exit();
    }
  });
  process.on('exit', function() {
    console.log('Over')
  })
}
clientsnum();

At times, I notice duplicates in the array and the value for "number" getting changed unexpectedly.

The exercise provides a template that I came across on other websites. While I understand the code, it doesn't seem to work as expected when I try using "process.stdin.on('end', ...)".

If anyone could provide some insights or explanations, I would highly appreciate it.

Below is the template provided:

function main(input) {
  process.stdout.write("hello " + input) //write output
}

process.stdin.resume()
process.stdin.setEncoding("utf-8")

var stdin_input = ""

process.stdin.on("data", function(input) {
  stdin_input += input          //read input from stdin
})

process.stdin.on("end", function (){
  main(stdin_input)
})

Answer №1

After a refreshing shower on my second day, I found the perfect solution.

let numOfCustomer = null;

let orderIDArray = [];

let answerArray = [];

let queryList = ["Enter number of customers: ", "Order ID: "];

function inquire() {
  process.stdout.write(queryList[0]);

  process.stdin.on("data", function (data) {
    answerArray.push(parseInt(data.toString().trim()));
    numOfCustomer = answerArray[0];

    if (answerArray.length < numOfCustomer + 1) {
      process.stdout.write(queryList[1]);         // Waiting for the answer to this question

      if (answerArray.length !== 1) {             // Need to wait for the next iteration/loop
        orderIDArray.push(answerArray[answerArray.length - 1]);
      }
    } else {
      orderIDArray.push(answerArray[answerArray.length - 1]);   // Getting the last loop answer
      process.exit();
    }
  });

  process.on("exit", function () {
    // debugging
    console.log(
      `All set! The answers are [${answerArray}], with a total of ${numOfCustomer} clients and their respective Order IDs [${orderIDArray}] `
    );
  });
}

inquire();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Power of Jasmine Testing with Ternary Conditions

Imagine a scenario where we are working with the following snippet of JavaScript code. object = _.isUndefined(object) ? '' : aDifferentObject.property; Is it possible to write a Jasmine test that covers both scenarios? Do we need to use two se ...

What is the best way to identify identical companies, consolidate them into a single entity, and combine their weights for a more

I've been experimenting with various methods such as filter, reduce, and includes, but I'm struggling to grasp the concept of how to solve this. Here is an array of objects that I have: [ { name: 'GrapeCo', weight: 0.15 }, { name: ...

Having trouble with submitting an Ajax form to a MySQL database

My expertise lies in PHP and HTML, but I'm currently learning JavaScript. I'm facing a challenge with creating a form that can submit data to be inserted into MySQL without reloading the page (using AJAX). Here is the form I have: <form id=" ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

How can I manage asynchronous calls when querying Mongoose for each element in an array using Express?

Having trouble with the post method below because of a mongoose async issue. The code res.send(suggestions) is being executed before Expense.findOne.exec. app.post('/suggestions', async function(req, res) { const suggestions = await req.body ...

Determine the moment at which the input is altered by adjusting the slider

I'm encountering an issue with making this work. My goal is to calculate input bmi_val whenever one of the other 2 inputs is modified. These inputs can be changed either directly by the user (entering a value into one of them) or through a jQuery sli ...

"Combining Cloud9 with sails.js and phpMyAdmin for optimal development experience

I'm facing an issue while trying to set up a basic sails.js application in the Cloud9 environment and connecting it to MySQL. Here are the steps I've followed: Created a Cloud9 project Installed sails: npm -g install sails Created the project: ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

Animation event in CSS3 fails to trigger on Firefox browser

Exploring the potential of CSS3 animation to detect when an input transitions from the enable to disable state, I encountered a challenge specifically in Firefox. Here is the code snippet that showcases the issue: View Demo on jsFiddle HTML: <input t ...

Utilizing Phantom Js with Apache server

After creating a JavaScript app, I realized the importance of making it SEO friendly. I am curious if anyone has experience setting up a crawlable webpage on Apache using Backbone.js (potentially with assistance from PHP and .htaccess files, or with Phant ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

Using jQuery's $.Deferred in conjunction with the window object's top.postMessage()

I am having trouble understanding how to effectively use $.Deferred. I currently have a situation similar to window.top.postMessage(mystring, myorigin); This works without any issues. I don't need assistance with sending/receiving postMessage What ...

What are some ways to adjust the page being served in node.js?

I have set up my server.js file with necessary dependencies and routing for handling POST requests. However, I am looking to dynamically update the webpage served by this server when a POST request is received on /message endpoint. These requests are trigg ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...