Event-driven programming for Node.js can be tricky for beginners, but this does not mean it is difficult to get started. This article will introduce the basics of Node.js and explain why it is popular.
To get started with Node.js, you must first understand the difference between Node.js and traditional server-side scripting environments such as PHP, Python, or Ruby.
You are likely to be familiar with asynchronous programming; after all, it is "A" in AJAX. Each function in Node is asynchronous. Therefore, all operations that usually block threads are executed in the background using Promise. This is the most important thing about Node. For example, if you are reading a file on a file system, an asynchronous function will be used.
If you are using some version of Node functions, use callback functions, which were designed before the Promise appears. Most Node functions now have Promise equivalents, so it is best to convert the callback function used here to a Promise-based equivalent and compare the syntax.
With Node, you have to do a lot of work yourself. For example, HTTP modules are very streamlined and not stick to specific styles. This may be overwhelming for beginners, but the benefit is the ability to build high-performance web applications (although JavaScript's performance is largely attributed to the V8-optimized engine). One script handles all communications with all clients. This greatly reduces the amount of resources the application uses. For example, here is a simple Node.js application code:
const i, a, b, c, max; max = 1000000000; var d = Date.now(); for (i = 0; i <p> Here is the equivalent code written in PHP:</p><pre class="brush:php;toolbar:false"> $a = null; $b = null; $c = null; $i = null; $max = 100000000; $start = microtime(true); for ($i = 0; $i <p> Now let's look at the benchmark data. The following table lists the response times in milliseconds for these two simple applications:</p><pre class="brush:php;toolbar:false"> const http = require('http');
http variable.
In the above code, we pass the name of the module to the exports object and populate its properties and methods with the snippet of code to be exposed. Consider the following module example:
exports.area = function (r) { return Math.PI * r ** 2; }; exports.circumference = function (r) { return 2 * Math.PI * r; };
This code creates an exports object. These functions can be accessed outside the module because they are defined on the PI and are completely protected from external interference. So you can rest assured that circuitference() will always work as expected (just provide a value for the import keyword):
// file import myModule from "./myModule.js" // Node built-in/package import http from "http"
In a browser, ESM can only search with relative file paths, as shown above. However, in Node, you can pass paths without the node: prefix.
However, the previous method only works for default exports. If you are using named exports (more on this later), you will need to use a slightly different syntax.
import { exportOne, exportTwo } from "./myModule.js"
To export content, use the export default keyword. export is used for named exports, and export default is used for default exports. Named export allows you to export different content and use only one of them in different modules using the import syntax above. If you export only one content, it will be easier to export by default.
// Name export function exportOne() { ... } export function exportTwo() { ... } // Default export default function defaultFunction() { ... }
In the rest of this tutorial, we will use ESM.
Node is a JavaScript environment running in Google's V8 JavaScript engine. Therefore, we should follow the best practices we use in client development. For example, we should avoid putting anything into the global scope. However, this is not always possible. The global scope in Node is (window in the browser), and you can easily create global variables of a function by omitting var when declaring variables.
Naturally, we need to install Node before writing and executing the application. If you are using Windows or macOS, installation is very simple; the nodejs.org website provides installers for these operating systems. For Linux, use any package manager. For example, if you are using a distribution that supports apt, open a terminal and type:
sudo apt-get update sudo apt-get install node
or:
sudo aptitude update sudo aptitude install node
Node.js is located in the sid repository; you may need to add them to your source list:
sudo echo deb https://ftp.us.debian.org/debian/ sid main > /etc/apt/sources.list.d/sid.list
But be aware that installing the sid package on older systems may damage your system. Be careful and delete module_name.
Of course, our first Node.js script will print the text "Hello World!" displayed in the console.
Let's go ahead and have a more advanced application; it's not as complicated as you think. Let's start with the following code. Read the comments and then read the explanation below:
// Includes http module. import { createServer } from "http" // Create a server. The function passed as a parameter is called every time the request is made. // The request variable saves all request parameters // The response variable allows you to perform any action on the response sent to the client. createServer(function (request, response) { // Attach the listener to the end event. // This event is called when the client sends all data and waits for a response. request.on("end", function () { // Write the header to the response. // 200 is the HTTP status code (this code indicates success) // The second parameter saves the header field in the object // We are sending plain text, so Content-Type should be text/plain response.writeHead(200, { 'Content-Type': 'text/plain' }); // Send data and end the response. response.end('Hello HTTP!'); }); // Listen to port 8080. }).listen(8080);
This code is very simple. You can send more data to the client by using response.end() . Save this code as http.js and type the following command in the console:
node http.js
Open the browser and navigate to https://www.php.cn/link/7232a90ea7d391905f9ee07bcc7c5967 . You should see the text Hello HTTP! on the page.
As mentioned earlier, we have to do all the work in the Node ourselves, including parsing the request parameters. However, this is quite simple. Take a look at the following code:
// Include createServer import { createServer} from "http" // and url modules, which are very useful in parsing request parameters. url = require("url"); // Create a server. createServer(function (request, response) { // Attach the listener to the end event. request.on('end', function () { // parse request parameters and store them in the _get variable. // This function parses the url from the request and returns the object representation. var _get = url.parse(request.url, true).query; // Write the header to the response. response.writeHead(200, { 'Content-Type': 'text/plain' }); // Send data and end the response. response.end('Here is your data: ' _get['data']); }); // Listen to port 8080. }).listen(8080);
This code uses the query attribute, which retrieves the parameters of the URL. Save this file as get.js and execute it with the following command:
node get.js
Then, navigating to the data parameter does not interrupt the script.
To manage files in Node, we use the fs module (core module). We use the fs.writeFile() method to read and write files respectively. I will explain the parameters after the following code:
// Include createServer, import { createServer } from "http" // and fs function import { readFile, writeFile } from "fs" // Create an http server. createServer(function (request, response) { // Attach the listener to the end event. request.on("end", function () { // Read the file. readFile("test.txt", 'utf-8', function (error, data) { // Write to the header. response.writeHead(200, { 'Content-Type': 'text/plain' }); // Increment the number obtained from the file. data = parseInt(data) 1; // Write incrementing numbers to the file. writeFile('test.txt', data); // End the response with some nice messages. response.end('This page was refreshed ' data ' times!'); }); }); // Listen to port 8080. }).listen(8080);
Save this as files.js . Before running this script, create a file named test.txt in the same directory as files.js .
This code demonstrates the fs.writeFile() method. Each time the server receives a request, the script reads a number from the file, increments that number, and writes the new number to the file. The fs.writeFile() method accepts file name and data as parameters. It also accepts the third and fourth arguments (both optional), specifying the encoding and callback functions respectively.
Now let's run this script with the following command:
node files.js
Open it in the browser at https://www.php.cn/link/7232a90ea7d391905f9ee07bcc7c5967 and refresh it a few times. Now, you might think there is an error in your code because it seems to be incremented twice. This is not a mistake. Each time this URL is requested, two requests are sent to the server. The first request is automatically issued by the browser, which requests favicon.ico , and of course the second request is for the URL ( https://www.php.cn/link/7232a90ea7d391905f9ee07bcc7c5967 ).
Even if this behavior is not technically wrong, it is not the behavior we want. We can easily fix this by checking the request URL. The following is the modified code:
// Include createServer, import { createServer } from "http" // and fs function import { readFile, writeFile } from "fs" // Create an http server. createServer(function (request, response) { // Attach the listener to the end event. request.on('end', function () { // Check whether the user requests/ if (request.url == '/') { // Read the file. readFile('test.txt', 'utf-8', function (error, data) { // Write to the header. response.writeHead(200, { 'Content-Type': 'text/plain' }); // Increment the number obtained from the file. data = parseInt(data) 1; // Write incrementing numbers to the file. writeFile('test.txt', data); // End the response with some nice messages. response.end('This page was refreshed ' data ' times!'); }); } else { // Indicates that the requested file was not found. response.writeHead(404); // and end the request without sending any data. response.end(); } }); // Listen to port 8080. }).listen(8080);
Now test it; it should work as expected.
Most traditional server-side technologies have built-in methods to connect to and query the database. With Node.js, you have to install a library. In this tutorial, I chose the stable and easy-to-use node-mysql . The full name of this module is mysql@2.0.0-alpha2 (all content after @ is version number). Open the console, navigate to the directory where you have stored the scripts, and execute the following command:
npm install mysql
This will download and install the module, it will also create the node_modules folder in the current directory. Now let's see how to use it in your code; see the following example:
// Includes http module, import { createServer } from "http" // and the mysql module you just installed. import * as mysql from "mysql" // Create a connection. // The data defaults to the new mysql installation and should be changed according to your configuration. const connection = mysql.createConnection({ user: "root", password: "", database: "db_name" }); // Create an http server. createServer(function (request, response) { // Attach the listener to the end event. request.on('end', function () { // Query the database. connection.query('SELECT * FROM your_table;', function (error, rows, fields) { response.writeHead(200, { 'Content-Type': 'x-application/json' }); // Send data as a JSON string. // Rows variable saves the result of the query. response.end(JSON.stringify(rows)); }); }); // Listen to port 8080. }).listen(8080);
Querying a database using this library is easy; just enter the query string and callback function. In a real application, you should check for errors (undefined if an error occurs) and send the response code based on the success or failure of the query. Also note that we have set x-application/json, which is a valid MIME type for JSON. Use JSON.stringify()
method to convert rows to JSON structure.
Save this file as mysql.js and execute it (if you have MySQL installed):
node mysql.js
Navigate to https://www.php.cn/link/7232a90ea7d391905f9ee07bcc7c5967 in your browser and you should receive a prompt to download the JSON format file.
Node.js requires extra work, but the rewards of a fast and powerful application are worth it. If you don't want to do all the work at the lowest level, you can always choose a framework (such as Express) to simplify the development of your application.
Node.js is a promising technology and an excellent choice for high-load applications. Companies like Microsoft, eBay and Yahoo have proven this. If you are unsure of hosting your website or application, you can always use a cheap VPS solution or a variety of cloud-based services such as Microsoft Azure and Amazon EC2. Both services offer scalable environments at reasonable prices.
The above is the detailed content of Node.js for Beginners. For more information, please follow other related articles on the PHP Chinese website!