今天我们会覆盖这些东西:
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.
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
var replaceTmpl = function(str, conf) { return("" + str).replace(/\$(\w+)\$/g, function(a, b) { return typeof conf[b] != "undefined" ? conf[b] : "$" + b + "$" }); }; var ret = replaceTmpl("pre_$str$_suffix", {str: "HELLO"}); console.log(ret);
process.on('uncaughtException', function(err) { console.log('got an error: %s', err.message); process.exit(1); }); setTimeout(function() { throw new Error('fail'); }, 100);
当同时有好几个请求的时候,Node会通知操作系统(通过 epoll, kqueue, /dev/poll, or select) 如果有新连接来了
吼一声,然后它就睡觉去了。。。只有当新连接来了,操作系统会把它拽醒,它才执行一下回调。于是每个请求对它来说,
就是小菜一碟。而不像其它大多数的 Web Server都会分配一个线程(2MB)去处理。
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
/usr/sbin/ab -n 10000 -c 10 http://localhost:8080/
/usr/sbin/ab -n 100000 -c 1000 http://localhost:8080/
支持各种常用的存储系统
以最常用的 mysql 为例子,https://github.com/felixge/node-mysql
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end();
类似于 Java 的 Connection Pool,nodejs也有 Connection Pool
以最常用的 mysql 为例子
var mysql = require('mysql'); var pool = mysql.createPool({ host : 'example.org', user : 'bob', password : 'secret' }); pool.getConnection(function(err, connection) { // Use the connection connection.query( 'SELECT something FROM sometable', function(err, rows) { // And done with the connection. connection.end(); // Don't use the connection here, it has been returned to the pool. }); });
var io = require('socket.io').listen(9090); io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
Zhang Guangda