Home >Web Front-end >JS Tutorial >Learning Server-Side JavaScript With Node.js
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.
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.
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.
npm -v
to view the npm version.Also, if you search for Node in your program, you should find the Node.js command prompt.
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.
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
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");
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
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/");
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! .
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/");
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.
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
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); }) })
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>
Please note that nairobi can be replaced with any city of your choice. Here are the results you should get.
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!