what's the node?
node 是一个运行在google的javascript引擎V8上的服务端程序,语言使用javascript.node.js 具有事件驱动、非阻塞的I/O和跨设备运行等优点。简单来说,node是可以运行在服务器端的、高效轻便的应用程序。
node can do?
node能快速建立一个web server :
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');
更多的内容可以访问node的官方网站:http://nodejs.org/ 和node的中文社区:http://cnodejs.org/
win7下安装node:
1、从官方网站http://nodejs.org/下载安装包:node-v0.6.14.msi 点击安装即可;我下载的最新安装包没有路径选择,默认安装在C:\Program Files\nodejs\里,安装过程其实就是解压和配置环境变量,如果需要更改路径,直接移动nodejs 文件夹,然后更改环境变量即可。
开始编写node:
1、建立demo.js 文件,文件内容:
var http=require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
var body='<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<h1>Hello World</h1>'+
'</body>'+
'</html>';
res.writeHead(200, {"Content-Type": "text/html"});
res.write(body);
res.end();
}).listen(1337,'127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
在cmd命令行下输入命令:node demo.js ,在浏览器中输入http://localhost:1337 即可看到打印结果:
简单的模板导入:
新建html.js文件,内容如下:
function getHtml(){
return '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<h1>Hello World</h1>'+
'</body>'+
'</html>';
}
exports.getHtml=getHtml;
而上面的demo.js内容更改如下:
var http=require('http');
var html=require('./html.js');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
var body=html.getHtml;
res.writeHead(200, {"Content-Type": "text/html"});
res.write(body);
res.end();
}).listen(1337,'127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
在cmd命令行下输入命令:node demo.js ,在浏览器中输入http://localhost:1337 即可看到相同的结果。
关于NPM
NPM是node的一个包管理工具,你可以用它把项目安装和发布到node程序里。liunx用户可以到官网下载:http://npmjs.org/;node的window版安装包默认就包含了npm工具,无需单独安装。
使用NPM导入项目十分简单,在命令行输入:npm install xxxx;如导入coffeeScript包,则只需输入:npm install coffee-script.
NPM有一个资源库,地址 https://registry.npmjs.org/,他会从这个地址获取资源,然后安装到本地。具体NPM用法,请看这一篇文章:如何使用NPM。
以上只是关于node的一些基础知识,随着深入的了解,或许你会像我一样喜欢上这东西。