Home >Web Front-end >JS Tutorial >Blocking and non-blocking calls of node.js callback functions

Blocking and non-blocking calls of node.js callback functions

PHPz
PHPzOriginal
2016-05-16 15:32:311439browse

First of all, node.js, as a JavaScript running platform, adopts event-driven and asynchronous programming. Through event registration and asynchronous functions, developers can improve resource utilization and server performance can also be improved. Secondly, for front-end people, node.js is the running platform for js. We can write system-level or server-side javascript code and hand it over to node.js for execution, so that our front-end people can also act on the background. In contrast , the browser-side JavaScript code will be subject to various security restrictions when running, and has limited operations on the client system, while node.js is a comprehensive background runtime that provides JavaScript with many functions that other languages ​​can achieve. .

Let’s get back to the topic. First, I will introduce blocking calls to you. Please read below for details.

1. Blocking call (read the file before performing subsequent operations)

var fs = require("fs");
var data = fs.readFileSync('/fs.txt');
console.log(data.toString());
console.log("程序执行结束!");

Output result:

"File content"

"Program execution ends!"

2. Non-blocking calls (reading files and other operations are performed synchronously)

var fs = require("fs"); 
fs.readFile('/fs.txt',function(err,data){
if(err) return console.error(err);
console.log(data.toString());
});
console.log("程序执行结束!");

Output result:

"Program execution ends!"

"File content"

The above content is the node introduced by the editor The entire content of blocking calls and non-blocking calls of .js callback functions, I hope you like it.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Statement:
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