Node.js, npm
Node.js is a JavaScript runtime environment that runs on a web server and includes the JavaScript engine built by Google. Node.js allows developers to use JavaScript as the language for building the Web API.
npm, or Node Package Manager, is also part of Node.js.
Install Node.js
Interactive Shell - REPL (Read-Eval-Print-Loop)
Node.js supplies an interactive shell that reads and evaluates code that you enter directly or load from a file.
To launch REPL, type node at the command line.
You can now enter any JavaScript code at the command prompt and it will be executed.
Displaying Output
There isn't a user interface on the server. Your code can use the global console.log method to display results to the console.
External Script Files
You can execute the code in a file by passing the filename to Node.js on the command line.
In your test folder, create a file named script.js with the content below.
Execute the script as follows.
Node.js does not have the window object that is available in a web browser because Node.js is running on the server.
Creating a Node Application
Create a new folder, cd into the folder and run the npm init command
This will create a file named "packages.json" in the project root directory. This file is used by npm to track the modules it installs.
Installing Packages - npm install [package-name]
.Installing the express package, installed 50 packages that were dependencies of the express package. All packages are installed in a folder named "node_modules". This folder is typically set up to be ignored by git commits because a project can have a huge number of modules and they can easily be installed from scratch from the packages.json file using the npm install command without a package specified.
After a modules has been added, the packages.json file is updated to include the new module in the "dependencies" section.
Creating a Basic Web Server
In some web frameworks the web server handles the web requests and routes them to the web API handlers. In Node.js, you have to create the web server that responds to the initial incoming web requests and handle the routing to the request handlers in our code.
Create a file named "server.js" and add the following code to create a web server. require is how you include external modules in your code. It is different that the ES 6 Modules "import/export" functionality. We'll cover modules in a separate topic.
Server.js
Start the Service
Request in Browser
Now, let's load a HTML document, instead of just writing text to the response.
Server.js
Index.html
Resources
There are other npm commands for updating modules to the latest version, removing modules, etc. Many of them are explained in further detail in the following tutorial.
Last updated