node基础06:回调函数

1.Node异步编程

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

异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了。

回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都支持回调函数。

例如,我们可以一边读取文件,一边执行其他命令,在文件读取完成后,我们将文件内容作为回调函数的参数返回。这样在执行代码时就没有阻塞或等待文件 I/O 操作。这就大大提高了 Node.js 的性能,可以处理大量的并发请求。

//server.js
var http = require("http");
var openfile = require("./openfile");

http.createServer(function(res, res){
    res.writeHead(200, {"Content-Type":"text/html; charset=uf-8"});
    if (res.url!=="/favicon.ico") {
        console.log('begin visit');
        res.write('hello world');
        openfile.readfile('./test.txt');
        console.log('异步加载完毕');
        res.end('end');
    }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
// readfile.js
var fs = require("fs");

module.exports = {

    //异步读取
    readfile: function(path){
        fs.readFile(path, function(err, data){
            if (err) {
                console.log(err)
            } else {
                console.log(data.toString());//data为一个buffer
            }
        })
    },

    //同步读取
    readfileSync:function(path){
        var data = fs.readFileSync(path, 'utf-8');
        console.log(data.toString());//data为一个buffer
        console.log("同步方法执行完毕");
        return  data;
    }
}
// test.txt
test-messagewelcome!

异步:

同步:

原文地址:https://www.cnblogs.com/noper/p/6244553.html