码迷,mamicode.com
首页 > Web开发 > 详细

Node.js回调函数

时间:2017-11-30 19:18:19      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:api   txt   阻塞   ring   实现   input   文件   哈哈   测试文件   

Node.js异步编程的直接体现就是回调。

异步编程依托于回调来实现,但是不能说使用了回调后程序就异步话了,回调函数在完成任务之后会被调用,Node使用了大量的回调函数,Node所以的API都是支持回调函数的。如下是阻塞和非阻塞的例子。

阻塞代码实例:

首先创建一个文件input.txt,如下内容:

这个是一个测试文件,O(∩_∩)O哈哈哈~。

创建main.js,代码如下:

var fs=require("fs");

var data=fs.readFileSync(‘input.txt’);

console.log(data.toString());

console.log("the program  execute to the end");

非阻塞代码:

main.js的代码:

fs=require(‘input.txt‘);

fs.readFile(‘input.txt‘,function(error,data){

if(error)return console.error(error);

console.log(data.toString());

});

console.log("the program  execute to the end");

Node.js回调函数

标签:api   txt   阻塞   ring   实现   input   文件   哈哈   测试文件   

原文地址:http://www.cnblogs.com/VARForrest/p/7930406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!