關於Node.js介紹,咱們引用官網(http://nodejs.org/)的一段文字說明:html
1
|
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
|
Google Chrome瀏覽器基於V8的,它是一個開源的JavaScript引擎,可以編譯和執行JavaScript代碼,在執行速度上有很大的優點。使用Node.js可以很容易地構建快速、可擴展的網絡應程序,它使用了事件驅動、非阻塞I/O模型實現,具備輕量、高效的特色,適合於構建運行在分佈地設備之上的數據密集型實時應用程序。
下面經過參考各類資料,從各個方面,歸納地總結一下Node.js,是咱們對Node.js有一個直觀的瞭解:node
- 使用JavaScript運行於服務端的平臺上,天然繼承了JavaScript語言的一些特性;
- Node.js基於單線程、基於非阻塞I/O模型實現;
- 適合於數據密集型應用,不適用於計算密集型類的應用(如算法等);
- 經過使用回調函數,來避免同步地等待I/O操做完成;
- Node.js非核心模塊很是多,質量可能良莠不齊(使用別人貢獻的模塊,要有承擔風險的準備);
- 由於簡單,開發Node.js應用程序效率很高;
- 調試相對困難,調試工具可能沒有其餘一些比較成熟的語言(如Java、C++等)的好用;
- Node.js基於事件驅動架構,events模塊是Node.js最核心的模塊。
我學習Node.js使用的工具及其環境配置,以下表所示:mysql
工具/環境 | 版本 | 功能 |
Node.js | 0.10.28 | Node.js平臺 |
CentOS | 6.4 | 操做系統環境 |
npm | 1.4.9 | Node包管理器(Node Package Manager) |
Python | 2.6.6 | Node.js依賴環境(Linux系統下) |
Eclipse | Kepler Service Release 2 | Node.js調試工具 |
安裝配置linux
安裝步驟,以下所示:git
1
2
3
4
5
|
cd /usr/local
sudo tar xvzf node-v0.10.28-linux-x64.tar.gz
sudo ln -s /usr/local/node-v0.10.28-linux-x64 /usr/local/node
sudo chown -R shirdrn:shirdrn /usr/local/node*
|
配置內容:github
1
2
3
|
vi ~/.bashrc
export PATH=$PATH:/usr/local/node/bin
. ~/.bashrc
|
Node包管理器(npm)web
和Python等語言同樣,在Node.js中能夠使用npm來管理package,經常使用的命令,以下所示:算法
命令語法 | 說明 | 示例 |
npm -l | 顯示npm命令的用法信息 | npm -l |
npm install <pkg> | 安裝包(package) | npm install express |
npm install <pkg@version> | 安裝指定版本的包 | npm install express@4.4.3 |
npm ls | 顯示已經安裝的包 | npm ls |
npm uninstall <pkg> | 卸載已經安裝的包 | npm uninstall express |
npm update [pkg] | 更新包 | npm update或npm update express |
npm version | 查看npm版本號 | npm version或npm -v |
npm list | 當前目錄下已安裝的包 | npm list |
npm list -g | 當前系統下已經安裝的包 | npm list -g |
npm view <pkg> | 查看某個包的信息 | npm view express |
npm view <pkg> version | 查看某個包的版本號 | npm view express version |
npm view <pkg> dependencies | 查看某個包的依賴 | npm view express dependencies |
npm outdated | 查看安裝哪些包有新版本發佈 | npm outdated |
npm publish <tarball> | 發佈包 | npm publish mynodejs.tar |
npm unpublish <project>[@<version>] | 取消發佈包 | npm unpublish mynodejs@1.0.2 |
npm init | 初始化包(產生package.json) | npm init |
npm tag <project>@<version> [<tag>] | 打tag | npm tag mynodejs@1.1.0 stable |
使用上面的命令能夠方便地管理Node.js包。sql
node工具chrome
使用node工具運行Node.js腳本很是容易,語法格式以下所示:
1
|
node [options] [ -e script | script.js ] [arguments]
|
有三種執行方式:
- 運行腳本
好比,運行腳本debug.js,執行以下命令便可:
1
|
node debug.js
|
- 運行代碼
若是,想要直接在命令執行代碼段,能夠使用-e選項,例如:
1
|
node -e
'console.log("hello")'
;
|
其中-e選項後面是一個代碼的字符串,他會轉換成JavaScript代碼在Node.js運行時環境執行,相似eval函數,將執行字符串中的代碼。
- REPL模式運行
能夠直接根據輸入node命令,而後回車,根據前導提示符,輸入命令執行,通常用來測試比較直觀。
調試Node.js代碼
能夠使用Eclipse開發工具,安裝Chrome Developer插件:
http://chromedevtools.googlecode.com/svn/update/dev/
這個是在線安裝地址。
例如,咱們在Eclipse中新建一個debug.js文件,代碼以下所示:
1
2
3
4
5
6
|
// say hello example
var
customer =
'shirdrn'
;
var
f =
function
(name) {
console.log(
'Hello, '
+ name +
'!'
);
}
f(customer);
|
而後,在Shell終端啓動調試:
1
|
node --debug-brk=9222
/home/shirdrn/nodejs/debug
.js
|
接着,能夠在Eclipse中對debug.js的代碼設置斷點,執行Debug As => Debug Configurations => 選擇Standalone V8 VM,建立一個調試配置,而後能夠調試運行,在斷點處查看變量的值。
編程實踐
- 使用核心模塊events
events模塊是Node.js最核心的模塊,經過使用該模塊,能夠了解Node.js的事件機制。下面代碼是註冊2個事件:一個是解析命令行傳入參數的parseCommand事件,另外一個是執行Shell命令的executeCommand事件。當腳本啓動執行時,發射一個parseCommand事件,把命令行傳遞的參數傳遞給該事件函數,解析參數構造Linux下Shell命令行完成後,會發射一個executeCommand事件,去執行這個Shell命令。
實現代碼,以下所示:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#!/usr/bin/env node
var
process = require(
'process'
);
var
taskShell = require(
'task-shell'
);
var
events = require(
'events'
);
var
bash =
'/bin/bash'
;
// create event emitter
var
emitter =
new
events.EventEmitter();
// register event: 'parseCommand'
emitter.on(
'parseCommand'
,
function
(argv) {
var
shell =
''
;
console.log(
'argv.length='
+ argv.length);
if
(argv.length >= 2) {
for
(
var
i=2; i<argv.length; i++) {
shell +=
' '
+ argv[i];
console.log(
'shell='
+ shell);
}
}
console.log(
'Parsed shell cmd: '
+ shell);
// emit
emitter.emit(
'executeCommand'
, shell);
});
//register event: 'executeCommand'
emitter.on(
'executeCommand'
,
function
(shellCmd) {
console.log(
'Execute shell cmd: '
+ shellCmd);
if
(shellCmd !=
''
) {
shellCmd = bash +
' '
+ shellCmd;
var
shell =
new
taskShell();
shell.run([], {command : shellCmd}, console);
console.log(
'Shell cmd executed.'
);
}
});
console.log(
'Passed cmd line: '
+ process.argv);
emitter.emit(
'parseCommand'
, process.argv);
|
- 建立一個HTTP服務器
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
#!/usr/bin/env node
var
port = 8080;
var
host =
'192.168.1.115'
;
console.log(
'Confiugre: host='
+ host +
', port='
+ port);
var
http = require(
'http'
);
var
server = http.createServer(
function
(req, res) {
res.writeHead(200, {
'Content-Type'
:
'text/plain'
});
res.end(
'Welcome to our site!!!'
);
});
console.log(
'Server created: '
+ server);
server.listen(port, host);
|
在運行前,首先要安裝http模塊:
1
|
npm install http
|
而後運行腳本(debughttp.js):
1
|
node debughttp.js
|
訪問http://192.168.1.115:8080/,能夠看到響應的消息內容。
- 使用express框架建立HTTP服務器
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
#!/usr/bin/env node
var
express = require(
'express'
);
var
app = express();
app.use(
function
(req, res, next) {
console.log(
'%s : %s'
, req.method, req.url);
next();
});
app.use(
function
(req, res, next) {
res.send(200, {
'hit'
:
'www.shiyanjun.cn'
});
});
app.listen(8080);
|
運行腳本,訪問http://192.168.1.115:8080/,能夠看到響應的JSON格式數據內容。擴展一下,你能夠寫一個HTML表單,經過表單提交數據到上面的地址,而後在代碼中經過req來接收參數數據,而後進行處理,最後響應請求。
- 文件讀寫
01
02
03
04
05
06
07
08
09
10
11
12
|
#!/usr/bin/env node
var
fs = require(
'fs'
);
var
file =
'/etc/passwd'
;
var
encoding =
'UTF-8'
;
fs.readFile(file, encoding,
function
(err, data) {
if
(err) {
console.error(err);
}
else
{
console.log(data);
}
});
|
- 使用socket.io、socket.io-client、process、util模塊
下面實現的腳本,是一個服務端和客戶端簡單會話的邏輯,腳本名稱爲endpoint.js,首先須要安裝socket.io、socket.io-client、process這三個模塊。
下面代碼執行,能夠經過從命令傳遞選項參數,選擇啓動服務器,仍是鏈接到服務器,代碼實現以下所示:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#!/usr/bin/env node
var
port = 8080;
var
host =
'192.168.1.115'
;
var
util = require(
'util'
);
var
startServer =
function
() {
var
http = require(
'http'
);
var
server = http.Server();
var
io = require(
'socket.io'
)(server);
io.on(
'connection'
,
function
(socket) {
console.log(
'Connected!'
);
// emit version infomation
socket.emit(
'welcome'
, {
'version'
:
'3.5.2'
,
'token'
:
'32jfds456FDSOwewA219bMqx4lPsz2'
});
socket.on(
'report'
,
function
(data) {
console.log(
'Reported data: '
+ util.inspect(data));
// do something
console.log(
'Computed!'
);
});
socket.on(
'close'
,
function
() {
console.log(
'Closed!'
);
});
});
console.log(
'Start server.'
);
server.listen(port, host);
};
var
startClient =
function
() {
var
client = require(
'socket.io-client'
);
socket.on(
'welcome'
,
function
(data){
console.log(
'Get welcome info from server: '
+ util.inspect(data));
var
version = data[
'version'
];
var
token = data[
'token'
];
console.log(
'version='
+ version +
', token='
+ token);
// do something
var
reportData = {
'alive'
: [
'node-01'
,
'node-06'
,
'node-03'
],
'dead'
: [
'node-8'
]};
console.log(
'Report data: '
+ util.inspect(reportData));
socket.emit(
'report'
, reportData);
socket.emit(
'close'
);
});
};
var
process = require(
'process'
);
var
argv = process.argv;
console.log(
'Passed arguments: '
+ argv);
var
option = argv[2];
if
(
'server'
== option) {
startServer();
}
else
if
(
'client'
== option) {
startClient();
}
else
{
console.error(
'Unknown augment: '
+ option +
'!'
);
}
|
啓動服務器,執行以下命令行:
1
|
node endpoint.js server
|
啓動鏈接服務器,執行以下命令行:
1
|
node endpoint.js client
|
- 使用mysql模塊鏈接MySQL數據庫
首先要安裝mysql、dateformat(格式化日期)模塊:
1
2
|
npm install mysql
npm install dateformat
|
下面是使用Node.js操做MySQL的代碼實現:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#!/usr/bin/env node
var
mysql = require(
'mysql'
);
var
util = require(
'util'
);
var
dateFormat = require(
'dateformat'
);
var
config = {
'host'
:
'192.168.1.105'
,
'port'
:
'3306'
,
'user'
:
'shirdrn'
,
'password'
:
'shiyanjun'
};
var
connect =
function
() {
var
connection = mysql.createConnection(config);
if
(connection) {
console.log(
'Succeed to connected: '
+ util.inspect(connection));
}
else
{
throw
new
Error(
'Fail to connect MySQL database!'
);
}
return
connection;
}
var
query =
function
(sql, callback) {
// connect to MySQL
try
{
var
connection = connect();
}
catch
(err) {
console.error(util.inspect(err));
throw
err;
}
// execute SQL queries
connection.query(sql, callback);
connection.end();
console.log(
'Connection closed!'
);
}
// query example
var
querySQL =
'SELECT id, host, port, updated_at FROM domain_db.traffic_proxy LIMIT 0,10'
;
query(querySQL,
function
(err, rows, fields) {
if
(err) {
throw
err;
}
for
(
var
i=0; i<rows.length; i++) {
var
row = rows[i];
var
host = row[
'host'
];
var
port = row[
'port'
];
var
updatedAt = dateFormat(row[
'updated_at'
],
'yyyy-MM-dd hh:mm:ss'
);
console.log(
'Record: host='
+ host +
', port='
+ port +
', updatedAt='
+ updatedAt);
}
});
|
上面代碼,從MySQL數據庫中的一個表中查詢數據,而後打印出來。
想進一步深刻理解Node.js,能夠參考相關文檔,主要包括Node.js提供的一些特性,如繼承(還有JavaScript具備的一些特性)。Node.js還有不少的模塊,經過學習來開發本身Node.js應用程序。
參考連接
- http://nodejs.org/
- https://www.npmjs.org/
- https://www.npmjs.org/doc/
- https://www.npmjs.org/package/express
- https://github.com/visionmedia/express/wiki/New-features-in-4.x
- http://expressjs.com/4x/api.html
- https://www.npmjs.org/package/socket.io
- https://www.npmjs.org/package/socket.io-client
- https://www.npmjs.org/package/mysql
- https://github.com/felixge/node-mysql
- https://www.npmjs.org/package/dateformat
- Node Web Development(David Herron)
開源項目
下面是我找到的一些Node.js開源項目,能夠選擇其中一些,經過閱讀代碼來全面熟悉Node.js: