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));
};
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":43},{\"line\":0,\"ch\":44}]]"}
!@%STYLE%@!
  • 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

2.2. Running your JavaScript file with Node.js

2.3. Running individual JavaScript commands

Summary

sitemap