Receiving User Input via Command Line Arguments
The first argument in the process.argv array is always the location of the Node.js binary that the program is running on. We are mainly interested in the arguments entered by the user, not the default arguments that Node.js provides.
Accessing Environment Variables
Now that you can collect data from the user, let's collect data from the program environment. The env object stores all the environment variables that are available when Node.js is running the program.
Accessing a Specified Environment Variable
Note that many of the environment variables you see depend on your system's configuration and settings, and your output may look significantly different from what you see here. Again, keep in mind that the output of this code will likely be different than what you see here, as it is specific to your system.
Retrieving An Argument in Response to User Input
The second line prints the environment variable stored in the first element of args; that is, the first command line argument the user supplied. At this point you can now access the value of any environment variable on your system.
Viewing Multiple Environment Variables
Getting individual variables is good, but it would be better if the user could specify how many variables they want. Now you have a way to get the variables that the user requests, but we still need to handle the case where the user enters the wrong data.
Handling Undefined Input
It would be more helpful for a user to see an error message if their command line argument was not found in the environment. Get the value of the command line argument in the environment and store it in a variable envVar.
Starting and Stopping the REPL
Executing Code in the Node.js REPL
Mastering REPL Shortcuts
Math.E Math.LN10 Math.LN2 Math.LOG10E Math.LOG2E Math.PI Math.SQRT1_2 Math.SQRT2 Math.abs Math.acos Math.acosh Math.asi n.
Using REPL Commands
The file is saved in the same directory where you opened the Node.js REPL. In the same directory where you saved peanuts.js, start the Node.js REPL with node.
Creating a package.json File
First, you'll create a package.json file to store useful metadata about the project and help you manage the dependent modules of the Node.js project. Once the information matches what you see here, press ENTER to complete this process and create the package.json file.
Now that you have your package.json file, you can test the installation of modules in the next step. If no lock file is available, it reads from the package.json file to determine installations.
It will also help to be familiar with the Node.js REPL (Read-Evaluate-Print-Loop). If you need more information on this, you can read our guide on how to use the Node.js REPL.
Creating a Module
To install this on macOS or Ubuntu 18.04, follow the steps in Install Node.js and create a local development environment on macOS or Install using a PPA section of Install Node.js on Ubuntu 18.04. To get this experience, follow How to use Node.js modules with npm and package.json, specifically Step 1 - Create a package.json file. If this was a module you wanted to publish to npm, you would answer all these prompts with relevant data, as explained in Using Node.js modules with npm and package.json.
All functions and objects stored in a module's export object will be displayed when other Node.js modules import it.
Testing your Module with the REPL
You then added an allColors property to the export object that references the local constant allColors array created earlier in the script. In the next step, you will use your module in other applications to demonstrate the effects of exporting. The REPL shows us the value of colors, which are all the functions and objects imported from the index.js file.
You will then apply these same concepts and load your module into your application as you would in a real project.
Saving your Local Module as a Dependency
It will then randomly select a color using the getRandomColor() function provided by the module. Finally, it will print a message to the console telling the user which color to use. You have now successfully installed the color module and can manage it like any other npm package used in your project.
However, if you've added more colors and features to your local color module, you'll need to run npm update on your apps to be able to use the new options.
Linking a Local Module
If that function functionA() calls another function functionB(), then functionB() is added to the top of the call stack. If so, the first entry in the message queue is moved to the call stack. Once the code is in the callback function, it will not write to the file until the HTTP request is completed.
We then use the axios.get() method to send an HTTP request to the API.
Writing a Node Module
For example, if we have an array with three elements called x, and create a new variable y such that y = x, y and x both refer to the same thing.
Manually Testing the Code
Next, let's use automated testing in Node.js and see if we can solve this problem with the Mocha testing framework.
Writing Your First Test with Mocha and Assert
A check mark on the left side of the test case means that the test passed. Let's change the test so that it only succeeds if we have absolutely no tasks in stock. Let's consider a situation where we have shared our module with some other developers and now they are giving us feedback.
Let's see how we'll need to adapt our newfound testing habits to work with asynchronous code.
Testing Asynchronous Code
Our function takes a callback function that will be used when the file write is complete. Our test will do two things: verify that the file exists in the first place, and then verify that it has the correct content. If our test code was outside the callback, it would fail as long as the code was called before the file write was complete.
The fs.existsSync() function returns true if the file path in the argument exists, otherwise false.
Using Hooks to Improve Test Cases
You can get started by checking out our guide on writing and running your first program in Node.js.
Creating a Basic HTTP Server
If you are not familiar with asynchronous programming in Node.js or the fs module for interacting with files, you can learn more with our article on How to write asynchronous code in Node.js. If you want to learn more about modules in Node.js, check out our article How to create a Node.js module. It only exits if it encounters an error that causes it to crash and close, or if we stop the Node.js process running the server.
The server then sent that response to cURL, which displayed the message on our terminal.
Returning Different Types of Content
Let's modify the requestListener() function to return the appropriate header from all JSON responses. Make sure you exit the running server with CTRL+C so we can go back to the standard terminal prompt. In this case, we signal to the browser that this CSV file is an attachment and should be downloaded.
It is common for HTML to be written in a file, separate from the server side code like our Node.js programs.
Serving an HTML Page From a File
To serve HTML files, we load the HTML file with the fs module and use its data when writing our HTTP response. This module contains a readFile() function that we will use to load the HTML file into place. To learn more about asynchronous programming best practices, you can read our guide How to write asynchronous code in Node.js.
We finally send the client the HTML page we loaded, with the data in the content variable.