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

Node.js 学习

时间:2017-07-17 18:34:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:传递   并发   inpu   lis   input   void   var   同步   第一个   

回调函数处理并发。

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);

 

Node.js 学习

标签:传递   并发   inpu   lis   input   void   var   同步   第一个   

原文地址:http://www.cnblogs.com/duasonir/p/7196508.html

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