|
Navigation
Recherche
|
Node.js tutorial: Get started with Node
mercredi 12 novembre 2025, 10:00 , par InfoWorld
Anytime you need to run JavaScript on the server—be it for a systems utility, a REST API, data processing, or anything else—Node is an excellent choice. There are newer runtimes, namely Deno and Bun, but Node remains the standard for server-side JavaScript. Also see: 10 JavaScript concepts you need to succeed with Node. Getting started with Node If you haven’t already experienced Node, this article will introduce you. We’ll step through installing Node and the NPM package manager, spinning up a simple web server, and using the Node cluster module to take advantage of multiple CPU cores. We’ll also look at using the NPM package manager to install additional Node modules and other JavaScript packages. And we’ll dip a toe into using a Node framework, in this case the ubiquitous Express server, to create more feature-rich and flexible Node.js servers. Let’s get started! Installing Node and NPM There are a few ways to install Node, including the installer that Node itself provides, but the recommended way is with a version manager. The most common version manager is NVM. This makes it easy to install Node and change versions when you need to. (There is also a Microsoft Windows-specific version called nvm-windows.) NVM can be installed with an installer or using a CLI. In the following example, we use curl: $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash Once you have NVM installed, installing the most recent version of Node is simple: $ nvm install latest The install latest command makes the latest version available. Mine is Node 24.9.0, so I activate it with: $ nvm use 24.9.0 Anytime you need to install another version of Node, you can use nvm install and nvm use to switch between them. You should now see Node available at your command prompt: $ node -v v24.9.0 When you install Node this way, the Node package manager (NPM) is also installed: $ npm -v 11.6.0 Note that using NVM also avoids potential permissions issues with NPM packages when using the installer. A simple web server in Node To start simply, we can use an example from the Node homepage. Copy the Synopsis example code as directed there and paste it into your code editor, then save it as example.js: const http = require('node:http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, InfoWorld!n'); }); server.listen(port, hostname, () => { console.log(`Server running at }); Open a shell in the directory where you saved the file, and run the file from your command line: $ node example.js Server running at You can now go to the browser and check it out at 127.0.0:3000, and you should see the greeting shown here: Matthew Tyson Back at the terminal, press Control-C to stop the running server. Before we go further, let’s pull apart the code. Creating a simple HTTP server with Node We start with the command: const http = require(‘http’); This is how you include a module in your code, in this case, the standard http module. (The http module ships with Node, so you don’t have to add it as a dependency.) This module provides the createServer and listen functions we’ll use later on. You might have noted that this example used a CommonJS import. While older, this style of import is still very common in Node programs as well as some documentation. However, it’s gradually being phased out in favor of ES Modules (ESM), the standardized module system introduced in ECMAScript 2015. An ESM import would look like this: import http from 'http'; After we import the http module, we define a couple of values we need (hostname and port): const hostname = '127.0.0.1'; const port = 3000; Next, we create the server: const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader(‘Content-Type’, ‘text/plain’); res.end(‘Hello Worldn’); }); The creatServer command accepts a callback function, which we define using the fat arrow notation. The callback function passes two arguments, the request (req) and response (res) objects needed to handle HTTP requests. The req argument contains the incoming HTTP request, which in this case is ignored. The res.end method sets the response data to ‘Hello InfoWorldn’ and tells the server that it is done creating the response. Next, we have: server.listen(port, hostname, () => { console.log(`Server running at }); The server.listen function accepts three arguments. The first two are the port and hostname, and the third is a callback that is executed when the server is ready (in this case, it prints a message to the console). Having all the event handlers defined as callbacks is one of the most subtle and powerful parts of Node. It’s key to Node’s asynchronous non-blocking architecture. Node.js runs on an event loop, which always reverts to handling events when not otherwise engaged. It’s like a busy order-taker continually picking up orders and then updating the order-maker with their order. We receive updates via the callbacks. A multi-process web server with Node Node’s asynchronous, non-blocking nature makes it good at handling many parallel requests, but it’s not truly concurrent by default. There are a few ways to make a Node application use multiple threads for true concurrency. One of the simplest is to use the PM2 project, which lets you run the same Node application in many processes. By launching each application instance in its own process, the operating system can make use of multiple cores on the machine. This is not usually a concern at first, but it’s a key performance consideration to bear in mind. You can install PM2 globally like so: $ npm install -g pm2 For our example, we want to make it obvious that the different processes are handling requests. We can achieve that goal with a small change to the server: res.end(`Hello, InfoWorld! Handled by ${process.pid}`); The process.pid field is a built-in environment variable, providing a unique ID for the currently running process in Node. Once PM2 is installed and the app is updated, we can run it like so: $ pm2 start example.js -i max That should launch several instances of the same program, as shown here: Matthew Tyson Then, if you open multiple windows, you can see the unique ID of each instance: Matthew Tyson An Express web server with Node For our final example, we’ll look at setting up an Express web server in Node. This time we’ll use NPM to download Express and its dependencies. NPM is one of the greatest storehouses of software on the planet, with literally millions of libraries available. Knowing how to use it is essential for working with Node. NPM works just like other package managers you may have used, letting you define and install dependencies in a structured way. To install Express, go to your project directory and type: $ npm install express Node should respond with something like: added 68 packages in 5s. You will notice several directories have been added to a /node_modules directory. Those are all the dependencies needed for Express. You usually don’t have to interact with node_modules yourself, but it’s good to know that’s where things are saved. Now look at the package.json file, which will have something like this in it: { 'dependencies': { 'express': '^5.1.0' } } This is how dependencies are defined in NPM. It says the application needs the express dependency at version 5.1.0 (or greater). Setting up the Express server in Node Express is one of the most-deployed pieces of software on the Internet. It can be a minimalist server framework for Node that handles all the essentials of HTTP, and it’s also expandable using “middleware” plugins. Since we’ve already installed Express, we can jump right into defining a server. Open the example.js file we used previously and replace the contents with this simple Express server: import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, InfoWorld!'); }); app.listen(port, () => { console.log(`Express server at }); This program does the same thing as our earlier http module version. The most important change is that we’ve added routing. Express makes it easy for us to associate a URL path, like the root path (‘/’), with the handler function. If we wanted to add another path, it could look like this: app.get('/about', (req, res) => { res.send('This is the About page.'); }); Once we have the basic web server set up with one or more paths, we’ll probably need to create a few API endpoints that respond with JSON. Here’s an example of a route that returns a JSON object: app.get('/api/user', (req, res) => { res.json({ id: 1, name: 'John Doe', role: 'Admin' }); }); That’s a simple example, but it gives you a taste of working with Express in Node. Conclusion In this article you’ve seen how to install Node and NPM and how to set up both simple and more advanced web servers in Node. Although we’ve only touched on the basics, these examples demonstrate many elements that are required for all Node applications, including the ability to import modules. Whenever you need a package to do something in Node, you will more than likely find it available on NPM. Visit the official site and use the search feature to find what you need. For more information about a package, you can use the npms.io tool. Keep in mind that a project’s health depends on its weekly download metric (visible on NPM for the package itself). You can also check a project’s GitHub page to see how many stars it has and how many times it’s been forked; both are good measures of success and stability. Another important metric is how recently and frequently the project is updated and maintained. That information is also visible on a project’s GitHub Insights page.
https://www.infoworld.com/article/2257958/nodejs-tutorial-get-started-with-nodejs.html
Voir aussi |
56 sources (32 en français)
Date Actuelle
jeu. 13 nov. - 01:37 CET
|








