1. 程式人生 > >Node.js 學習

Node.js 學習

con world web put 這也 error 對象 回調函數 oid

回調函數處理並發。

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 學習