Speaker : Claude Jiang
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.
Talk is cheap. Show me the code.
- Linus Torvalds
//load third party module 'colors'.
var colors = require('colors');
//print out 'Hello Node.js' with colorized.
console.log("Hello Node.js".rainbow);
$.ajax({
url: 'http://www.claudejiang.com/echo',
data: {param1: 'claude'},
success: function(data){
...
}
});
var fs = require('fs');
fs.readFile('text.txt', {encoding: 'UTF-8'}, function(err, data){
if(err) throw err;
console.log(data);
});
console.log('end.');
var fs = require('fs');
var rs = fs.createReadStream(__filename);
rs.on('data', function(data){
// console.log(data);
console.log(data.toString());
});
rs.on('end', function(){
console.log('end');
});
// rs.pipe(process.stdout);
// load net module
var net = require('net');
// create a tcp server
var server = net.createServer(function (socket) {
socket.on('data', function(data){
socket.pipe(socket);
});
});
// bind to port 7000 on localhost
server.listen(7000, "localhost");
console.log("TCP server listening on port 7000 at localhost.");
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 io = require('socket.io').listen(80);
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>
Any application that can be written in JavaScript, will eventually be written in JavaScript.
var fs = require('fs');
var path = require('path');
var files = fs.readdirSync('.'); // cpu wait
files.forEach(function(file){
var stat = fs.statSync(file); // cpu wait
if(stat.isFile()){
var str = fs.readFileSync(file, {encoding: 'utf8'}); // cpu wait
console.log(file + ":" + str.length);
}
});
var fs = require('fs');
var path = require('path');
fs.readdir('.', function(err, files){
if(err) return console.log(err);
files.forEach(function(file){
fs.stat(file, function(err, stat){
if(stat.isFile()){
fs.readFile(file, {encoding: 'utf8'}, function(err, str){
console.log(file + ":" + str.length);
});
}
});
});
});
I hear and I forget. I see and I remember. I do and I understand.
不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之;学至于行之而止矣。- 荀子《儒效篇》