Just got back from the prompt.get function

Currently, I am utilizing the prompt package in Node to gather user input on the command line. However, my query lies in how I can store and access the return variable from prompt.get? As a newcomer to Node, I'm not entirely sure about the process.

const prompt = require('prompt');

prompt.start();
prompt.get(['num'], function (err: any, result: any) {
    if (err) { return Error(err); }
    if(result.num > 0) {
        return "Positive";
    }
    else {
        return "Negative";
    }
});

Cheers!

Answer №1

To avoid the issue of an empty variable, initialize it outside the callback function and then set its value inside the callback:

let value;

prompt.get(['num'], function (err: any, result: any) {
    if (err) { return Error(err); }

    value = result > 0 ? "Positive" : "Negative";
});

However, keep in mind that the value will still be empty until the callback is complete. Therefore, calling the variable immediately after may result in it being undefined.

let value;

prompt.get(['num'], function (err: any, result: any) {
    if (err) { return Error(err); }

    value = result > 0 ? "Positive" : "Negative";
});

console.log(value); // => undefined

If you prefer using promises, the package also supports that approach where you can utilize await, as demonstrated on their readme page:

(async () => {
    const { num } = await prompt.get(['num']);
})();

Take note of the self-executing async function used here as await only functions within async functions (though technically not required after node v15 & while using modules).

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

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

Sharing a Directive across multiple AngularJS modules: Tips and Tricks

AngularJS has truly captured my interest with its powerful capabilities. I am delving deeper into the world of Angular and finding myself falling in love with it more each day. Despite my efforts, certain doubts continue to linger, leaving me eager for cla ...

JkMegaMenu drop-down menus in Chrome are shifting to the left when the window is resized

Currently, I am utilizing the JKmegamenu plugin to incorporate a megamenu into a website that is currently under development. The megamenu functions properly and has an attractive appearance. However, there seems to be an issue where the drop-down divs shi ...

Error 404: Image not found in webpack

Can anyone help me with importing an image using the web pack configuration? After running yarn build on my app, I encountered an error in the console. How can I import an image from the assets/public folder to the dashboard file? (refer to the attached i ...

Adjust modal size dynamically from the middle with JavaScript and CSS

Take a look at this fiddle example: http://jsfiddle.net/c2mmQ/ In the fiddle, I have implemented a modal using jQuery that fades in and scales up with CSS animations when the show link is clicked. Inside the modal, there is another link that is supposed t ...

Using Selenium WebDriver to retrieve the row number that is visible within a table

As I write a test script using Selenium WebDriver and Java for a page containing a table with multiple rows and columns, I face the challenge of dealing with hidden rows alongside displayed ones. With around 1800 total rows, only seven are visible on the ...

Correct the spacing around periods, even within separate div elements

I am facing a challenge with a large json file resembling a decision tree, where each node contains a sentence. There are multiple buttons on the page, and each click on a button retrieves a node from the json to populate the HTML. The json structure: { ...

The callback function in jQuery ajax never triggered

Sample Javascript code utilizing jQuery 1.7: $( function() { $.get('/ajax_dummy', function() { alert('foo'); }) }); Upon inspecting with Firebug, I observed that the HTTP GET request was successfully sent and a "hello world" respo ...

Solving Issues with Image Rotation and Positioning

I am encountering difficulties when trying to reposition an image that has been previously rotated using the transform rotate property. Specifically, after rotating the image, the top and left attributes do not update accordingly, resulting in the image a ...

What is the best way to design versatile div containers that combine the float property with fluid dimensions?

I am attempting to achieve a specific layout where the width of the content_container extends up to the right side of the screen and dynamically adjusts based on whether the expandable pane is collapsed or expanded. Applying width: 100% to .content_contain ...

What other technique can I use to replace the creation of a jquery division?

I`m relatively new to all things related to web technologies and I am currently practicing and learning about them. On my practice page, I've experimented with various elements, including changing div heights based on the viewport height. Here's ...

VueJS ensures that instance properties are reactive

Currently, I am in the process of developing a VueJS plugin that utilizes instance properties. I find myself needing to reintroduce some reactive values back into VueJS. After conducting my research: I have been struggling to grasp the concept behind Obj ...

What methods can I use to integrate modifications to a library into my application?

I have encountered some issues with a library that I am currently using. As a newcomer to this project, I am unsure of how to proceed. Specifically, the problematic library is related to the windows-registry. I have identified two fixes that need to be ma ...

Cobalt does not reflect changes in React components when the component's state is updated

I am currently developing a small React application for Cobalt, and so far everything is running smoothly. However, I have encountered an issue with rerendering a specific portion of HTML when the component's state changes. The layout consists of a me ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Tips for sending the parent object through a jQuery.ajax success function

I'm currently working on a function that includes child functions and objects: //API load function var apiDataLoader = function () { // Set default settings this.apiSeason = '7924'; this.apiMatchDay = '30'; th ...

What are the limitations of using a CSS transition alongside a separate animation created with jQuery's animate method?

I am facing an issue with moving and flipping a button simultaneously when clicked. I have set up two animations to happen at the same time, each with the same duration. However, only the CSS scale transform seems to be working while using both jQuery&apos ...

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

Disabling the browser's back button initially allows users to go back, but then forces them to browse forward instead

I need to prevent the user from being able to navigate back to the previous page in their browser. To achieve this, I have included the following code snippet in the layout pages of my ASP.NET MVC application (in addition to setting appropriate response h ...