原稿:语雀 · 快速上手 · 原目录:Node.js › 快速上手

参考链接:how2j nodejs教程 廖雪峰 nodejs

一个最简单的server

var http = require('http');
var url=require('url'); //引入url模块,帮助解析
var querystring=require('querystring');// 引入querystring 库,帮助解析

function service(request,response){
    var arg = url.parse(request.url).query;
    var params = querystring.parse(arg);

    console.log("method - " + request.method);
    console.log("url - " + request.url);
    console.log("id- " + params.id);

    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello Node.js');
}
var server = http.createServer(service);
server.listen(8088);

上面就是使用node.js实现的最简单server,当访问127.0.0.1:8088是即可看到相关的输出


路由 & 模块化

  • 模块化:在node环境中,一个.js文件就称之为一个模块(module),模块提高了代码的可维护性、复用性。nodejs默认支持的模块化规范是CommonJS,使用require()加载和module.exports输出,与ES6的模块import/export有所不同,这种不同不仅仅是语法上的(可见Node.js 如何处理 ES6 模块
  • 仅考虑cjs时,模块导出也分module.exports和exports,二者区别可见廖雪峰在模块中的解释
  • 下面的server中使用了node自带的基本模块 http 和 url
  • 路由:一般的开发中需要根据不同的url对请求进行不同的处理,下面实现nodejs server的路由功能
2. 首先定义业务处理模块 src/requestHandlers.js ,这是实际对请求进行处理的函数
function listCategory() {
  return "a lot of categorys";
}

function listProduct() {
  return "a lot of products";
}

exports.listCategory = listCategory;
exports.listProduct = listProduct;
  1. 路由模块 src/router.js
function route(handle, pathname) {
  if (typeof handle[pathname] === "function") {
    return handle[pathname]();
  } else {
    return pathname + " is not defined";
  }
}
exports.route = route;
  1. 服务器模块 src/server.js
let http = require("http");
let url = require("url"); //引入url 模块,帮助解析

function start(route, handle) {
  function onRequest(request, response) {
    let pathname = url.parse(request.url).pathname;
    let html = route(handle, pathname);
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write(html);
    response.end();
  }

  http.createServer(onRequest).listen(8088);
}

exports.start = start;
  1. 入口模块 index.js
let { start }  = require('./src/server');
let { route } = require('./src/router');
let { listCategory, listProduct }  = require('./src/requestHandlers');

let handle = [];
handle["/listCategory"] = listCategory;
handle["/listProduct"] = listProduct;

start(route, handle);

执行时,只需要运行index.js,在控制台输入 node index.js,使用浏览器访问

总结:一个请求在node server端的处理流程:

  1. index.js 调用 server.start(),传递 router.route 函数和 handle 数组作为参数
  2. server.js 通过8088端口启动server,然后用 onRequest 函数来处理业务
  3. 在 onRequest 中,首先获取访问路径 pathname,然后调用 router.route(),传入 pathname 和 handle
  4. 在router.js 中,通过 pathname 匹配并执行真正的业务函数,返回执行结果
  5. 当访问 /listCategory的时候,listCategory() 就会被调用,并返回业务 Html 代码 : "a lots of categorys".
  6. 如果要扩展,比如 /listUser, 那么就只需要新增加 listUser 函数,并在 index.js 中对添加映射

使用MySQL

作为server,势必涉及到crud操作,这里演示node环境下对数据库的操作

首先准备数据表,见data.sql (0 KB)

之后在项目目录下通过npm安装mysql相关的依赖: npm install mysql –save

编写db.js和app.js(db.js (2 KB)app.js (0 KB)),其中:

  • open/closeConnection() 负责建立与关闭mysql和node之间的连接,在每次操作前建立,结束后关闭
  • showAll():所有数据
  • add(name):添加
  • remove(id):删除
  • get(id):指定id数据
  • update(id, name):更新

基本上所有操作都通过query()操作完成,传入sql语句和参数,执行结果会作为回调的参数,模式如下

openConnection();
connection.query(sql, params, (err, result) => {...})
closeConnection();