Computer scienceProgramming languagesJavaScriptInteraction with a browserBrowser Window

Taking input: sync-input library

3 minutes read

You already know how to take input from the terminal in JavaScript using the sync-input library. When you're working on your JavaScript project in the Hyperskill online code editor, this library is already included in your project. However, to run the same project in your local workspace and take input, you need to install this library first. In this topic, we will cover how to install and use the sync-input library to take input in your local environment.

As you know, Node.js enables you to run JavaScript outside of a browser window, so you can create web servers and CLI applications. Node executes these by running asynchronously and getting input from the terminal, which is a synchronous task. This makes it all a bit tedious to do.

Installation

Even though the sync-input library should come with the project, here's how you can install the library to your local project. Run the command in your terminal:

npm install https://github.com/hyperskill/sync-input/archive/v1.tar.gz

Alternatively, you can add the following line to your package.json file:

"dependencies": {
    "sync-input": "https://github.com/hyperskill/sync-input/archive/v1.tar.gz"
}

Don't forget to run the npm install command to install the above dependency.

Usage

After the installation, to start using the library you need to import it. You can use the require function for it:

const input = require('sync-input');

After the import, you can start using the library.

If you know a bit about Python, you can easily use this library as it's similar to the input function.

To take a string input from the terminal, just call the method that you've imported before:

let name = input();

After executing this script, the program will wait until the user presses the Enter key.

Conclusion

Taking input from the terminal can be tricky with JavaScript when it comes to CLI programs and projects on this platform. Our team made a library called sync-input to simplify taking input. In this topic, we've covered how to install and use it.

29 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo