• Node.js 学习


    回调函数处理并发。

    Sync 同步;

    var data = fs.readFileSync('input.txt');
    console.log(data.toString());


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

    阻塞是按顺序执行的,而非阻塞是不需要按顺序的,
    所以如果需要处理回调函数的参数,我们就需要写在回调函数内。

    事件驱动程序
    Node.js 使用事件驱动模型,当web server接收到请求,就把它关闭然后进行处理,然后去服务下一个web请求。
    当这个请求完成,它被放回处理队列,当到达队列开头,这个结果被返回给用户。
    这个模型非常高效可扩展性非常强,因为webserver一直接受请求而不等待任何读写操作。
    (这也被称之为非阻塞式IO或者事件驱动IO)


    emit 发出; 发射; 颁布; 发表;


    Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,
    require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。


    //main.js
    var hello = require('./hello');
    hello.world();

    //hello.js
    exports.world = function() {
    console.log('Hello World');
    }

    //hello.js
    function Hello() {
    var name;
    this.setName = function(thyName) {
    name = thyName;
    };
    this.sayHello = function() {
    console.log('Hello ' + name);
    };
    };
    module.exports = Hello;

    这样就可以直接获得这个对象了:
    //main.js
    var Hello = require('./hello');
    hello = new Hello();
    hello.setName('BYVoid');
    hello.sayHello();

    //Node.js 函数
    function say(word) {
    console.log(word);
    }

    function execute(someFunction, value) {
    someFunction(value);
    }

    execute(say, "Hello");

    // the same
    function execute(someFunction, value) {
    someFunction(value);
    }

    execute(function(word){ console.log(word) }, "Hello");

    我们在 execute 接受第一个参数的地方直接定义了我们准备传递给 execute 的函数。
    用这种方式,我们甚至不用给这个函数起名字,这也是为什么它被叫做匿名函数 。


    var http = require("http");

    http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
    }).listen(8888);

    var http = require("http");

    function onRequest(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
    }

    http.createServer(onRequest).listen(8888);

  • 相关阅读:
    应用市场高速下载以及网页端调起APP页面研究与实现
    linux系统下,添加硬盘并挂载到操作系统的shell 脚本范例
    linux系统下,新加硬盘并把现有的/home目录扩容。
    Java打印裴波那契数列
    JAVA排序的方法
    Java语言输出菱形图型
    Oracle中的sql脚本语言中的循环语句介绍
    Oracle存储过程的创建实例和调用实例
    数组常用方法3---新增元素
    数组常用方法2——修改数组元素。
  • 原文地址:https://www.cnblogs.com/duasonir/p/7196508.html
Copyright © 2020-2023  润新知