Node.js回调函数

Node.js回调函数 首页 / Node.js入门教程 / Node.js回调函数

一个函数被作为参数传递给另一个函数(在这里无涯教程把另一个函数叫做“otherFunction”),回调函数指在完成给定任务时在otherFunction中被调用。

如读取文件有两种模式:阻塞模式和非阻塞模式。

同步模式

创建一个名为 input.txt 的文本文件,其内容如下:

Learnfk Point is giving self learning content
to teach the world in simple and easy way!!!!!

使用以下代码创建一个名为 main.js 的js文件-

var fs=require("fs");
var data=fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");

现在运行main.js以查看输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/nodejs/nodejs-callbacks-concept.html

来源:LearnFk无涯教程网

$node main.js

验证输出。

Learnfk Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended

异步模式

创建一个具有以下内容的名为input.txt的文本文件。

Learnfk Point is giving self learning content
to teach the world in simple and easy way!!!!!

更新main.js以使其具有以下代码-

var fs=require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

现在运行main.js以查看输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/nodejs/nodejs-callbacks-concept.html

来源:LearnFk无涯教程网

$node main.js

验证输出。

Program Ended
Learnfk Point is giving self learning content
to teach the world in simple and easy way!!!!!

这两个示例解释了阻塞和非阻塞调用的概念。

  • 第一个示例显示程序阻塞,直到读取文件,然后才继续结束程序。

    无涯教程网

  • 第二个示例显示该程序不等待文件读取,而是继续打印" Program Ended",与此同时,不受阻碍的程序继续读取文件。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

结构会议力 -〔李忠秋〕

大厂广告产品心法 -〔郭谊〕

业务开发算法50讲 -〔黄清昊〕

程序员的个人财富课 -〔王喆〕

说透数字化转型 -〔付晓岩〕

分布式系统案例课 -〔杨波〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

深入拆解Tomcat & Jetty -〔李号双〕

好记忆不如烂笔头。留下您的足迹吧 :)