Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。 Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。 Node.js 的包管理器 npm,是全球最大的开源库生态系统。
安装、简易教程:http://www.runoob.com/nodejs/nodejs-tutorial.html
官方文档:http://nodejs.cn/api/
一、nodejs大致功能模块
二、部分用法示例
1、简单重要的使用命令
使用淘宝 NPM 镜像
npm install -g cnpm –registry=https://registry.npm.taobao.org
安装模块
cnpm install [模块名]
运行js文件
node [js文件名]
2、示例:请求参数获取
//router.js
function route(pathname) { pathname = pathname.substring(1, pathname.length); console.log("About to route a request for " + pathname); //var strs = pathname.split('&'); //for (var i = 0; i < strs.length; i++) { // console.log(strs[i]); //} if (pathname == 'testFun') { console.log('filename: ' + __filename); console.log('dirname: '+__dirname); testFun(); } } function testFun() { //for (var i = 0; i < 100000; i++) { // console.log("testFun "+i); //} // 输出当前目录 console.log('当前目录: ' + process.cwd()); // 输出当前版本 console.log('当前版本: ' + process.version); // 输出内存使用情况 console.log(process.memoryUsage()); } exports.route = route;
//server1.js
var http = require("http"); var url = require("url"); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; if (pathname != '/favicon.ico') { console.log("Request for " + pathname + " received."); route(pathname); } response.writeHead(200, { "Content-Type": "text/plain" }); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
//index.js
var server = require("./server1"); var router = require("./router"); server.start(router.route);//启动service,传入router处理函数 Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } function printHello() { console.warn("nodejs服务正常运行中! " + new Date().Format("yyyy-MM-dd hh:mm:ss")); } printHello(); // 两秒后执行以上函数 setInterval(printHello, 10000);
在代码文件目录执行cmd命令:node index.js
打开浏览器,请求:http://localhost:8888/test/001
效果:
3、示例:express使用
//express_demo.js 文件
/** 使用淘宝 NPM 镜像 npm install -g cnpm --registry=https://registry.npm.taobao.org * cnpm install body-parser --save cnpm install cookie-parser --save cnpm install multer --save */ var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser') var fs = require("fs"); var util = require('util'); //// 创建 application/x-www-form-urlencoded 编码解析 //var urlencodedParser = bodyParser.raw({ extended: false }) app.use(cookieParser()) app.use(express.static('Content')); app.use(bodyParser()); // 主页输出 "Hello World" app.get('/', function (req, res) { console.log("主页 GET 请求"); console.log("Cookies: ", req.cookies); //res.send('Hello GET'); // 输出 JSON 格式 response = { first_name: req.query.first_name, last_name: req.query.last_name }; console.log(response); res.send(JSON.stringify(response)); }) // POST 请求 app.post('/', function (req, res) { console.log("主页 POST 请求"); //res.send('Hello POST'); // 输出 JSON 格式 //请求json格式: {"first_name":"pkm","last_name":"test1"} 类型 application/json response = { first_name: req.body.first_name, last_name: req.body.last_name }; console.log("准备写入文件"); fs.writeFile('input.txt', util.inspect(req), function (err) { if (err) { return console.error(err); } console.log("数据写入成功!"); }); console.log(res); res.end(JSON.stringify(response)); }) var server = app.listen(8888, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })