Table of Contents
What is Node.js?
Install
Hello World!
Home Web Front-end JS Tutorial Learning Server-Side JavaScript With Node.js

Learning Server-Side JavaScript With Node.js

Mar 13, 2025 am 10:35 AM

Node.js: A modern framework for building high-performance real-time web applications

Node.js is an important framework in modern web development. It simplifies the creation process of high-performance, real-time web applications. Node.js allows JavaScript to be used end-to-end on both server-side and client-side. This tutorial will walk you through the installation of Node.js and demonstrate how to write the first "Hello World" program. Ultimately, you will learn how to build a weather API using Node.js and Express.

What is Node.js?

Traditionally, JavaScript can only run in web browsers, but Node.js came into being due to growing interest in bringing it to the server side.

Node.js is slightly different from other server technologies because it is based on events rather than threads. Web servers such as Apache used to serve PHP and other CGI scripts are thread-based because they generate a system thread for each incoming request. While this is sufficient for many applications, the thread-based model is not scalable when dealing with many long-term connections (e.g., the connections required for serving real-time applications, such as instant messaging applications).

"Every I/O operation in Node.js is asynchronous..."

Node.js uses event loops instead of threads and is able to scale to millions of concurrent connections. It takes advantage of the fact that the server spends most of its time waiting for I/O operations (e.g., reading files from hard disk, accessing external web services, or waiting for file uploads to complete) because these operations are much slower than memory operations. Each I/O operation in Node.js is asynchronous, which means that the server can continue to process incoming requests while the I/O operation is in progress. JavaScript is great for event-based programming because it has anonymous functions and closures, which makes defining inline callbacks a breeze, and JavaScript developers already know how to program this way. This event-based model makes Node.js very fast and makes scaling of real-time applications very easy.

  1. Install

Node.js officially supports Linux, macOS, Microsoft Windows, SmartOS and FreeBSD. To install the latest version of Node.js on Windows (v16 and later), your computer must be running Windows 8.1, 10, or 11.

Node.js has its own package manager built in, called Node Package Manager (npm for short), which allows you to install third-party modules from the npm registry.

  1. Download the latest version of Node.js from nodejs.org (the latest version is 17.9.0 at the time of writing and the latest LTS version is 16.14.2). This should download the .msi file on your computer.
  2. Run the file and complete the installation wizard. Most options are optional – unless you have good reason, there is no need to change the program path. You can choose to install Chocolatey (a Windows package manager) or skip this step.
  3. After the installation wizard is completed and Node.js is installed successfully, open the terminal and run npm -v to view the npm version.

Also, if you search for Node in your program, you should find the Node.js command prompt.

Learning Server-Side JavaScript With Node.jsLearning Server-Side JavaScript With Node.jsLearning Server-Side JavaScript With Node.jsLearning Server-Side JavaScript With Node.js The command prompt provides a REPL (Read-Evaluation-Print Loop) where you can type JavaScript Node.js code and evaluate the code immediately and output the result. You can also load JavaScript from external files into REPL sessions and more.

  1. Hello World!

Learning any new technology starts with the "Hello World!" tutorial, so we'll create a simple HTTP server to serve that message.

First, we will create a new Node.js project. To do this, open your terminal, switch to the directory where you want the project to be located, and run the following command:

 npm init
Copy after login

You will be prompted to provide some information about the library, including the library name, author, entry file, license and version. After completion, a package.json file will be created using the provided information. To skip this step, attach the require function as shown below (inside test.js ):

 var util = require("util");
Copy after login

This loads the util module, which contains utility functions for handling system-level tasks such as printing output to a terminal. To use a function in a module, call it on the variables that store the module—in this case, the node command with the file name as the parameter.

 node test.js
Copy after login

Running this command will output "Hello World!" on the command line.

To create an HTTP server, you must use the http module.

 var util = require("util");
var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Hello World!');
  res.end();
}).listen(8080);

util.log("Server running at https://localhost:8080/");
Copy after login

This script imports the http module and creates an HTTP server. The anonymous function passed to http.createServer() will be executed when the request is received. Visit http://localhost:8080/ in your browser and you will see Hello World! .

Learning Server-Side JavaScript With Node.js 3. A simple static file server

OK, we've built an HTTP server, but no matter which URL you visit, it will send nothing but "Hello World". Any HTTP server must be able to send static files such as HTML files, images, and other files. This is how the following code does:

 var util = require("util"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs");

http.createServer(function(request, response) {
    var uri = path.parse(request.url).base;
    var filename = path.join(process.cwd(), uri);
    fs.access(filename, fs.constants.F_OK, function(err) {
        if(err) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            response.end();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if(err) {
                response.writeHead(500, {"Content-Type": "text/plain"});
                response.write(err "\n");
                response.end();
                return;
            }

            response.writeHead(200);
            response.write(file, "binary");
            response.end();
        });
    });
}).listen(8080);

util.log("Server running at http://localhost:8080/");
Copy after login

We first need to use all modules in our code. This includes http , path and url modules, which parse the requested incoming URL and find the pathname of the accessed file. We use process.cwd() (or the current working directory) and the path to the requested file to find the actual file name on the server's hard drive.

Next, we check if the file exists, which is an asynchronous operation, so the callback function is required. If the file does not exist, a 404 Not Found message is sent to the user and the function returns. Otherwise, we use fs.readFile() to read the file. If you access http://localhost:8080/path/to/file in your browser, the file will be displayed in your browser.

Learning Server-Side JavaScript With Node.js 4. Build the Weather API in Node.js using Express

Based on our static file server, we will build a Node.js server that gets and displays the expected weather conditions for a given city. First, in this example, we will need two additional third-party modules: the axios module and the express module. Express is a web framework for building RESTful APIs in Node.js applications. We will use the Express module to build a single API endpoint that will fetch the city from each request and respond with an HTML body containing the city's forecast weather conditions. The weather information will come from the external API - so we will make API requests using axios client.

First, we will install the express and axios modules using the following commands at the same time:

 npm i express axis
Copy after login

This will install both modules from the npm registry. Replace app.get() code with the following code:

 app.get('/', (req, res) => {
    let city = req.query.city;

    axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apikey}`)
        .then((response) => {
            if(response.status === 200) {
                res.send(`The weather in your city "${city}" is<br>
                ${response.data.list[0].weather[0].description}`)
            }
        })
        .catch((err) => {
            console.log(err);
        })
})
Copy after login

We first retrieve the query string (city) from query property.

We then use axios to issue a GET request to the weather forecast API. The URL will require two variables: we want to get the forecasted city and the unique API key provided in the Open Weather API Information Center.

We set up a res.send() method. When an error occurs, we can log the error data to the console simply by running node test.js on the command line and typing the following URL into the browser:

 <code>http://localhost:3000/?city=nairobi</code>
Copy after login

Please note that nairobi can be replaced with any city of your choice. Here are the results you should get.

Learning Server-Side JavaScript With Node.js Next steps

Node.js is a very exciting technology that simplifies the creation of high-performance real-time applications. I hope you can see the benefits of it and be able to use it in some of your own applications. Because Node.js has a powerful module system, it's easy to use open source third-party libraries in your application, and almost everything has modules available: including a database connection layer, a template engine, a mail client, and even a complete framework for connecting all of this content.

I wish you a happy Node.js programming!

This article has been updated and contains contributions from Kingsley Ubah. Kingsley is passionate about creating content that educates and inspires readers. Hobbies include reading, football and cycling.

The above is the detailed content of Learning Server-Side JavaScript With Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles