My NodeJs learning summary (1)_node.js
In this first article, let’s talk about some programming details of NodeJs.
1. Traverse the array
for (var i=0, l=arr.length; i<l; i++)
One advantage of writing this way is that each loop saves one step to obtain the length of the array object. The longer the array length, the more obvious the value.
2. Determine whether the variable is true or false
if (a) {...} //a='', a='0', a=[], a={}
The results of if conditional judgment are: false, true, true, true. This result is different from PHP's result, don't be confused. It is also necessary to distinguish between situations where it is similar to non-identity judgments.
3. Judgment of non-identity of 0 value
1 if (0 == '0') {...} //true 2 if (0 == []) {...} //true 3 if (0 == [0]) {...} //true 4 if (0 == {}) {...} //false 5 if (0 == null) {...} //false 6 if (0 == undefined) {...} //false
In fact, there are many such weird judgments, I only listed the more common ones. If you want to understand the rules, please refer to my other blog post: [JavaScript] In-depth analysis of JavaScript’s relational operations and if statements.
4. The trap of parseInt
var n = parseInt(s); //s='010'
After this statement is executed, the value of n is 8, not 10. Although many people know this, mistakes are inevitable in programming, and I know it very well. Therefore, it is best to write in the following way and you will not make mistakes.
var n = parseInt(s, 10);
5. Variables must be declared before use
Although there is no error in using variables directly without declaring them, writing this way is very error-prone. Because the interpreter will interpret it as a global variable, it can easily have the same name as other global variables and cause errors. Therefore, we must develop a good habit of declaring variables before using them.
6. There is asynchronous situation in the loop
for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query为表查询操作,是异步操作 }
You will find that the output results are the same, and they are the output content when i=arr.length-1. Because JavaScript is single-threaded, it will first execute the synchronous content of the entire loop before executing the asynchronous operations. The anonymous callback function in the code is an asynchronous callback. When this function is executed, the for loop and some subsequent synchronization operations have been completed. Due to the closure principle, this function will retain the contents of the sql variable and i variable in the last loop of the for loop, so it will lead to wrong results.
So what should we do? There are two solutions. One is to use an immediate function, as follows:
for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; (function(sql, i){ db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query为表查询操作,是异步操作 })(sql, i); }
Another method is to extract the asynchronous operation part and write a function as follows:
var outputSQL = function(sql, i){ db.query(sql, function(){ sys.log(i + ': ' + sql); }); //db.query为表查询操作,是异步操作 } for (var i=0, l=arr.length; i<l; i++) { var sql = "select * from nx_user"; outputSQL(sql, i); }
7. When processing large amounts of data, try to avoid nested loops.
Because the processing time of nested loops will increase exponentially as the amount of data increases, it should be avoided as much as possible. In this situation, if there is no better way, the general strategy is to trade space for time, that is, to establish a Hash mapping table of secondary cyclic data. Of course, specific circumstances must be analyzed on a case-by-case basis. Another point to mention is that some methods themselves are a loop body, such as Array.sort() (this method should be implemented using two layers of loops), so you need to pay attention when using it.
8. Try to avoid recursive calls.
The advantage of recursive calling is that the code is concise and the implementation is simple, but its disadvantages are very important and are explained as follows:
(1) The size of the function stack will grow linearly with the recursion level, and the function stack has an upper limit. When the recursion reaches a certain number of levels, the function stack will overflow, causing program errors;
(2) Each recursive level will add additional stack push and pop operations, that is, saving the scene and restoring the scene during the function call.
Therefore, recursive calls should be avoided as much as possible.
9. Regarding scope isolation of module files.
When Node compiles the JavaScript module file, its content has been packaged head and tail, as follows:
(function(exports, require, module, __filename, __dirname){ 你的JavaScript文件代码 });
This allows scope isolation between each module file. Therefore, when you write NodeJs module files, you do not need to add a layer of scope isolation encapsulation yourself. The following code format only adds an extra layer of function calls, which is not recommended:
(function(){ ... ... })();
10. Don’t mix arrays and objects
The following is an example of an error code:
var o = []; o['name'] = 'LiMing';
Mixing arrays and objects may lead to unpredictable errors. One of my colleagues encountered a very strange problem. Let’s look at the code first:
var o = []; o['name'] = 'LiMing'; var s = JSON.stringify(o);
He originally thought that the name attribute of object o would be in the JSON string, but the result was that it was not. I was also very surprised at the time, but I had a hunch that it was a problem of mixing arrays and objects. I tried it and it turned out to be the problem. Later, I found out in the ECMA specification that arrays are serialized according to JA rules. Therefore, it is necessary to develop a good programming habit, use arrays and objects correctly, and do not mix them.
11. Elegant Promise Programming
I believe anyone who has come into contact with nodeJs has had this experience. When asynchronous callbacks are nested within asynchronous callbacks, the code becomes confusing and lacks readability. This dilemma of nodeJs can be overcome with the help of promises. Promise is like a carver, making your code elegant and beautiful. Promise has an A specification, and there are several implementation methods online, you can refer to it.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
