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.
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.
- 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.
- 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.
- 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.
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.
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
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! .
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/");
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.
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
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.
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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function