Node.js入门
Node.js是什么,这里就不再多说。经过我简单测试,执行相同的任务,Node.js(单进程)比Nginx+php快4倍,当然,这并不表示Node.js的性能就是Nginx+php的4倍,可能不同的任务场景表现各有差异。但这足以让我有兴趣去了解它了。
Node.js可以说就是js,作为php程序员,之前接触的js完全是围绕着浏览器工作的,现在改在服务器上工作了,还有一些不适应的地方,如下:
一,自定义模块
module.js
var cfg = {"info":"Require test."};
module.exports = {
print_hello : function() {
return "Hello,World!";
},
print_info : function() {
return cfg.info;
}
};
main.js
var m = require("./module.js");
console.log( m.print_info() );
二,接收参数
1,get.js
var http = require("http");
var url = require("url");
http.createServer(function(request,response) {
var $get = url.parse(request.url,true).query;
response.writeHead(200,{"Content-Type":"text/plain"});
response.end($get['data']);
}).listen(1337,'192.168.9.10');
console.log("'Server running at http://192.168.9.10:1337/");
2,post.js
var http = require('http');
var querystring = require('querystring');
http.createServer(function (request, response) {
var post_data = '';
request.addListener('data', function(post_chunk) {
post_data += post_chunk;
});
request.addListener('end', function() {
post_data = querystring.parse(post_data);
response.writeHead(200, {'Content-Type':'text/plain'});
response.end(post_data.username);
});
}).listen(1337, '192.168.9.10');
console.log("'Server running at http://192.168.9.10:1337/");
三,文件读写操作
fs.js
var fs = require('fs');
// 写入文件
fs.writeFile("./message.txt", "Write file testing.\n", function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
// 追加写入
fs.appendFile("./message.txt", "appendFile file testing.\n", function (err) {
if (err) throw err;
console.log('The "appendFile file testing." was appended to file!');
});
// 是否存在
fs.exists('./message.txt', function (exists) {
console.log( exists ? "it's there" : "not exists!" );
});
// 读取文件
fs.readFile('./message.txt', function (err, data) {
if (err) throw err;
console.log(data.toString());
});
Node.js官方文档:http://nodejs.org/api/