Lesson 2. Running a Node.js application

In this lesson, you write and run your first JavaScript file with Node.js. At the end, I show you how to import JavaScript files into REPL so you can work with prewritten code.

This lesson covers

  • Creating and saving a JavaScript file
  • Running your JavaScript file with Node.js
  • Loading files into REPL
Consider this

You’re testing some code that you’ve written in JavaScript. Suppose that this code is the function shown in the following snippet, which accepts an array of numbers and prints them to the screen.

Note

In this code example, I use ES6 syntax to assign the variable printNumbers to a function defined with a single arr parameter and an arrow symbol in place of the traditional function keyword. I use another arrow function as the callback function within my forEach call.

let printNumbers = arr => {                1
  arr.forEach(num => console.log(num));
};

  • 1 Print array elements.

To test whether this code works, you could save it in a .js file, link it to an .html web page, and run that file in a browser, viewing the results in your browser’s inspector window. With Node.js, you get immediate satisfaction by running JavaScript files directly in terminal.

2.1. Creating a JavaScript file

To get started with your first Node.js application, create a JavaScript file to print a message to the terminal console. To do that, follow these steps:

  1. Open your text editor to a new window.
  2. Type the following code in that empty file: console.log(Hello, Universe!);
  3. Save this file as hello.js on your desktop.

That’s all you need to do. You’ve created a JavaScript file that Node.js can execute. In the next section, you run that file.

Strict mode

In JavaScript, you can opt to write code in strict mode—a mode in which casual Java-Script mistakes are caught, even when the Node.js engine or web browsers you use let those mistakes pass.

To use strict mode, add “use strict”; to the top of every JavaScript file you write (before any other statements). For strict mode to work, all files in a related project must be tagged as using strict mode.

See strict mode’s documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.

Note

Strict mode changes some previously-accepted mistakes into errors, so they’re discovered and promptly fixed.

Some mistakes discovered by strict mode include

  • Accidentally creating global variables—You won’t be able to create a variable without the var, let, or const keywords.
  • Assigning variables that can’t be assigned—You can’t use undefined as a variable name, for example.
  • Using non-unique function parameter names or property names in an object lit-eral—You need to choose names that don’t repeat within the same scope when assigning values.
Note

JavaScript has retained "use strict"; as a string for backward compatibility. Older JavaScript engines see it as a string and ignore it.

JavaScript can be forgiving, but for learning purposes and in anticipation of the casual mistakes that most developers make, I use strict mode in my code and recommend that you do the same. Although I may not show "use strict"; in the book’s code examples, this line is present at the top of every JavaScript file I write and run.

2.2. Running your JavaScript file with Node.js

The Node.js JavaScript engine can interpret your JavaScript code from the terminal when you navigate to the location of a JavaScript file and preface the filename with the node keyword.

Complete the following steps to run your JavaScript file:

  1. Open a new terminal window.
  2. Navigate to your desktop by entering cd ~/Desktop.
  3. Run your JavaScript file by entering the node keyword followed by the file’s name. You can also run the same command without the file’s extension. Type node hello at the prompt, for example, for a file named hello.js (figure 2.1).
Figure 2.1. Running a JavaScript file with Node.js

If your file was created and run correctly, you should see Hello, Universe! printed on the screen. If you don’t see a response, make sure that hello.js has content in it and that your latest changes are saved. Also, make sure that you run the command from that file’s directory.

Exactly what is happening here? The Node.js console.log function allows you to output the result of any JavaScript command to the console window (or your terminal’s standard output window). If you’ve debugged JavaScript in your browser before, you’ll notice the parallel between using console.log in a Node.js console window and outputting to your debugging tool’s console window.

Tip

For more information about console.log and other logging types, please reference appendix B.

Quick check 2.1

Q1:

If you have a file called hello.js, what will happen if you run node hello in terminal?

QC 2.1 answer

1:

Because Node.js is primed for executing JavaScript code, it doesn’t require adding the .js file extension when running files. You could run a file as node hello.js or node hello; either will work.

 

2.3. Running individual JavaScript commands

Imagine that you’re working on an application to send positive messages to your users. Before you fully incorporate your file of positive messages into the application, you want to test it in your Node.js REPL. You create a .js file with your messages as an array by creating a JavaScript file called messages.js with the code from the following listing.

Listing 2.1. Declaring a JavaScript variable in messages.js
let messages = [
  "A change of environment can be a good thing!",
  "You will make it!",
  "Just run with the code!"
];                               1

  • 1 List an array of messages.

Instead of executing this file with Node.js (which currently wouldn’t offer anything), you initiate the REPL environment with the node keyword and import this file by using .load messages.js, as shown in listing 2.2. By importing the file, you give REPL access to the contents of that file. After the file is imported, the window responds with the file’s contents. You also have access to the messages variable in your REPL environment.

Note

Make sure that you start your REPL session from the same directory in which you saved the messages.js file; otherwise, you’ll need to import the absolute path of the file instead of its relative path. The absolute path to a file is its location on your computer, starting from your root directory. On my computer, for example, /usr/local/bin/node is the absolute path to my installation of Node.js. The relative path from the local directory would be /bin/node.

Listing 2.2. Loading a JavaScript file into REPL
> .load messages.js
"use strict";
let messages = [
  "A change of environment can be a good thing!",
  "You will make it!",
  "Just run with the code!"
];                              1

  • 1 Loading an array with three strings

You plan to list each of the messages to your users through your Node.js application. To test this list, loop through the array and broadcast each message by entering the code from the next listing directly in the REPL window.

Listing 2.3. Use a file’s contents in REPL
> messages.forEach(message => console.log(message));      1

  • 1 Log each message by using a single-line arrow function.

The messages print in their array order in the terminal window, as shown in the following listing.

Listing 2.4. Results from the console.log loop
A change of environment can be a good thing!
You will make it!
Just run with the code!
undefined                  1

  • 1 Printing messages and showing undefined as the return value

If you’re happy with the code you wrote in the REPL window, you can save the code to a file called positiveMessages.js by typing .save positiveMessages.js in REPL. Doing so saves you the trouble of retyping any work that you produce in the REPL environment.

Quick check 2.2

1

What are three ways in which you could exit the REPL environment?

2

How do you load a file that isn’t in your project folder into REPL?

3

What happens if you run .save with a filename that already exists?

QC 2.2 answer

1

To exit your Node.js REPL environment, you can type .exit, press Ctrl-C twice, or press Ctrl-D twice.

2

For files that aren’t located within the directory you navigated to in terminal, you may need to use that file’s absolute path.

3

Running .save saves your REPL session to a file and overwrites any files that have the same name.

 

Ease in navigating the Node.js REPL environment comes with practice. Remember to access node in terminal for quick checking and testing of code that might take longer to modify in a big application. Next, you’re off to start building web applications and setting them up the right way from scratch.

Summary

In this lesson, you learned that JavaScript files can be run with Node.js in your terminal. In your first outing with Node.js, you created and ran your first application. Then you explored the REPL environment by loading your JavaScript file and saving your REPL sandbox code. In the next lesson, you create a Node.js module and install tools with npm.

Try this

console.log will soon become one of your best friends in web development, as log notes will help you find bugs. Get to know your new friend with a little practice and variation. As mentioned earlier in this lesson, console is a global object in Node.js, from the Console class. log is only one of many instance methods you can run on this object.

Note

String interpolation means inserting a piece of text, represented by a variable, into another piece of text.

Try printing the following to console:

  • A message with an interpolated string variable with console.log(Hello %s,Universe);
  • A message with an interpolated integer variable with console.log(Score: %d, 100);

Try building a file called printer.js with the code in the next listing inside.

Listing 2.5. String interpolation example
let x = "Universe";
console.log(`Hello, ${x}`);     1

  • 1 Log an interpolated string.

What do you expect to happen when you run node printer.js in terminal?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset