Node.js 实现简单的接口服务器的实例代码
zhangjianying 人气:0通过Node.js来实现接口服务器的功能。主要特点为:
1) 增加接口不需要重启
2) 异步执行,但接口阅读的时候是同步的代码(从上而下),或者可以按需求并行,串行
这里只是抛出基本思路,所以使用GET,也没有加密之类的
首先启动监听端口,配置好访问规则。(通过识别特定URL ,动态执行相应的接口脚本)
----- |----HamstrerServlet | ------ command3G | ------ login.js //登录脚本(这里只是简单演示) | --- server.js (主启动脚本) | --- dbutil (数据库操作)
server.js
var $ = require('jquery'); var _ = require('underscore'); var vm = require('vm'); var fs = require('fs'); var journey = require('journey'); var async = require('async'); var dbutil = require('.https://img.qb5200.com/download-x/dbutil'); String.prototype.replaceAll = function(s1, s2) { var demo = this while (demo.indexOf(s1) != - 1) demo = demo.replace(s1, s2); return demo; } // Create a Router var router = new(journey.Router); // Create the routing table router.map(function() { // this.root.bind(function (req, res) { res.send("Welcome") }); this.get(/HamstrerServlet\/(\w*\W*\w*)*/).bind(function(req, res, id) { var runJsPath = this.request.url.pathname.replaceAll("/HamstrerServlet", "") + ".js"; console.log("执行的脚本文件:" + runJsPath); //传入的绑定变量 var sandbox = { req: req, res: res, $: $, dbutil: dbutil, async: async, console: console }; fs.readFile('./HamstrerServlet' + runJsPath, function(err, data) { vm.runInNewContext(data, sandbox, 'myfile.vm'); }); }); this.post('/^HamstrerServlet\/(\w*)$/)').bind(function(req, res, data) { res.send(200); }); }); require('http').createServer(function(request, response) { var body = ""; request.addListener('data', function(chunk) { body += chunk }); request.addListener('end', function() { router.handle(request, body, function(result) { response.writeHead(result.status, result.headers); response.end(result.body); }); }); }).listen(8080);
dbutil.js
var mysql = require('mysql'); //导入mysql Module var pool = mysql.createPool({ host: '192.168.140.237', user: 'root', password: '123456', database: 'command3G' }); //查询sql语句 function query(strSQL, param, callback) { pool.getConnection(function(err, connection) { connection.query(strSQL, param, function(err, rows, fields) { if (err) throw err; callback(rows, fields); connection.end(); // connection.destroy(); }); }); } exports.query = query;
login.js
console.log("beigin"); //并行处理,相当于2个map最后再做一个ReReduce async.parallel([ function(callback){ // 从数据库中获取当前时间 dbutil.query("SELECT CURTIME() AS DATE",null,function(rows,fields){ callback(null, rows[0].DATE); }); }, function(callback){ //随便返回一个值 callback(null, '中文测试'); } ], function(err, results){ console.log(results); var retVal ={ "currentTime": results[0], "desc": results[1] }; res.sendBody(JSON.stringify(retVal)); });
node server.js 启动后通过访问 http://localhost:8080/HamstrerServlet/command3G/login
就会输出:
这个时候修改login.js都会及时生效,不需要重新启动服务器
加载全部内容