Node.js 学习

回调函数处理并发。web

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());
});ui

阻塞是按顺序执行的,而非阻塞是不须要按顺序的,
因此若是须要处理回调函数的参数,咱们就须要写在回调函数内。this

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


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

相关文章
相关标签/搜索