赞
踩
// http://www.runoob.com/nodejs/nodejs-restful-api.html// // --Coding Standard// 1 Enforce Callback Error Handling (handle-callback-err)// https://eslint.org/docs/rules/handle-callback-err.html//// 2 Disallow string concatenation when using __dirname and __filename (no-path-concat)// https://eslint.org/docs/rules/no-path-concat#disallow-string-concatenation-when-using-__dirname-and-__filename-no-path-concat// Include All variables// //var express = require('express')var app = express()var fs = require('fs')var moment = require('moment')var ROOT_PATH = __dirnamevar JSON_FILE = 'users.json'var FILE_ECODE_TYPE = 'utf8'var fullJsonFilePath = ROOT_PATH + '/' + JSON_FILE// Define All Basic Functions// ///function ListUserActionFunc (req, res) { function GetFromJSONFunc (err, data) { if (err) { console.log(err.stack) } console.log('[%s]', moment().format('YYYY-MM-DD HH:mm:ss')) console.log(data) res.end(data) } fs.readFile(fullJsonFilePath, FILE_ECODE_TYPE, GetFromJSONFunc)}//// ///// 添加的新用户数据var addUser = { 'user4': { 'name': 'mohit', 'password': 'password4', 'profession': 'teacher', 'id': 4 }}function AddUserActionFunc (req, res) { function GetFromJSONFunc (err, data) { if (err) { console.log(err.stack) } data = JSON.parse(data) data['user4'] = addUser['user4'] console.log('[%s]', moment().format('YYYY-MM-DD HH:mm:ss')) console.log(data) res.end(JSON.stringify(data)) } // 读取已存在的数据 fs.readFile(fullJsonFilePath, FILE_ECODE_TYPE, GetFromJSONFunc)}function DeleteUserFunc (req, res) { console.log('hello DeleteUserFunc') function GetFromJSONFunc (err, data) { if (err) { console.log(err.stack) } var id = 2 console.log('hello GetFromJSONFunc') data = JSON.parse(data) delete data['user' + id] console.log('[%s]', moment().format('YYYY-MM-DD HH:mm:ss')) console.log(data) res.end(JSON.stringify(data)) } // First read existing users. fs.readFile(fullJsonFilePath, FILE_ECODE_TYPE, GetFromJSONFunc)}//// ///function GetIdFunc (req, res) { function GetFromJSONFunc (err, data) { if (err) { console.log(err.stack) } data = JSON.parse(data) var user = data['user' + req.params.id] console.log('[%s]', moment().format('YYYY-MM-DD HH:mm:ss')) console.log(user) res.end(JSON.stringify(user)) } // 首先我们读取已存在的用户 fs.readFile(fullJsonFilePath, FILE_ECODE_TYPE, GetFromJSONFunc)}function SocketListenerFunc () { var host = server.address().address var port = server.address().port console.log('Please visit http://%s:%s', host, port)}// Main Service Code// //app.get('/listUsers', ListUserActionFunc)app.get('/addUser', AddUserActionFunc)app.get('/deleteUser', DeleteUserFunc)app.get('/:id', GetIdFunc)var server = app.listen(8081, SocketListenerFunc)// Test URL// http://127.0.0.1:8081/listUsers// http://127.0.0.1:8081/addUser// http://127.0.0.1:8081/2// http://127.0.0.1:8081/deleteUser
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。