├── 1 ├── test.conf ├── config │ └── test.conf ├── timer.js ├── test.js ├── poll.js ├── practice │ ├── startServer.js │ ├── nextServer.js │ ├── sync.js │ └── async.js ├── setImmediate.js ├── queue.js ├── callback.js └── block.js ├── 3 ├── api-server │ ├── package.json │ └── lib │ │ └── baseMongodb.js ├── msvc │ ├── package.json │ ├── model │ │ └── content.js │ ├── controller │ │ └── content.js │ └── core │ │ ├── apiCenter.js │ │ └── baseMongodb.js ├── mvc │ ├── package.json │ ├── core │ │ ├── model.js │ │ ├── controller.js │ │ ├── apiCenter.js │ │ └── baseMongodb.js │ ├── model │ │ └── content.js │ └── util │ │ └── baseFun.js └── restful │ ├── package.json │ └── lib │ └── baseMongodb.js ├── 4 ├── express │ ├── myapp │ │ ├── package.json │ │ └── app.js │ └── myapp-async │ │ ├── package.json │ │ └── app.js └── koa │ └── myapp-async │ ├── package.json │ └── app.js ├── 5 ├── pm2 │ ├── data │ │ ├── err-0.log │ │ ├── err-1.log │ │ ├── info-0.log │ │ └── info-1.log │ ├── app.js │ └── pm2.config.js └── cluster │ ├── cluster.js │ └── app.js ├── 6 ├── api │ ├── package.json │ ├── core │ │ ├── model.js │ │ ├── controller.js │ │ ├── apiCenter.js │ │ └── baseMongodb.js │ ├── model │ │ └── content.js │ ├── controller │ │ └── test.js │ ├── util │ │ └── baseFun.js │ ├── pm2.config.js │ └── service │ │ └── content.js ├── cpu │ ├── package.json │ ├── core │ │ ├── model.js │ │ ├── controller.js │ │ ├── apiCenter.js │ │ └── baseMongodb.js │ ├── model │ │ └── content.js │ ├── controller │ │ └── test.js │ ├── util │ │ └── baseFun.js │ ├── pm2.config.js │ └── service │ │ └── content.js └── io │ ├── package.json │ ├── core │ ├── model.js │ ├── controller.js │ ├── apiCenter.js │ └── baseMongodb.js │ ├── model │ └── content.js │ ├── util │ └── baseFun.js │ ├── pm2.config.js │ ├── controller │ └── test.js │ └── service │ └── content.js ├── 7 ├── package.json ├── core │ ├── model.js │ ├── controller.js │ ├── apiCenter.js │ └── baseMongodb.js ├── model │ └── content.js ├── controller │ └── content.js └── util │ └── baseFun.js ├── 8 ├── src │ ├── middleware │ │ └── logCenter.js │ ├── controller │ │ ├── content.js │ │ └── localCache.js │ ├── core │ │ ├── model.js │ │ └── controller.js │ └── lib │ │ └── baseFun.js ├── app.js ├── package.json ├── log │ └── test.log └── pm2.config.js ├── 9 ├── src │ ├── middleware │ │ └── logCenter.js │ ├── controller │ │ ├── content.js │ │ └── localCache.js │ ├── core │ │ ├── model.js │ │ └── controller.js │ └── lib │ │ └── baseFun.js ├── app.js ├── package.json ├── log │ └── test.log └── pm2.config.js ├── 10 ├── src │ ├── middleware │ │ └── logCenter.js │ ├── controller │ │ ├── content.js │ │ └── localCache.js │ ├── lib │ │ ├── singleton.js │ │ └── baseFun.js │ └── core │ │ ├── model.js │ │ └── controller.js ├── app.js ├── package.json ├── log │ └── test.log └── pm2.config.js ├── 11 ├── bin │ └── send_request.js ├── src │ ├── middleware │ │ ├── logCenter.js │ │ └── session.js │ ├── controller │ │ ├── v1 │ │ │ └── test.js │ │ ├── memLeak.js │ │ ├── content.js │ │ └── localCache.js │ ├── lib │ │ ├── singleton.js │ │ └── baseFun.js │ └── core │ │ ├── model.js │ │ ├── controller.js │ │ └── apiCenter.js ├── log │ └── test.log ├── package.json ├── app.js └── pm2.config.js ├── 12 ├── disk_io │ ├── test_file.conf │ ├── package.json │ ├── index.js │ ├── lib │ │ └── v8_profiler.js │ └── package-lock.json ├── disk_io_opt │ ├── test_file.conf │ ├── package.json │ ├── lib │ │ └── v8_profiler.js │ ├── package-lock.json │ └── index.js ├── cpu │ ├── lib │ │ ├── md5.js │ │ └── v8_profiler.js │ ├── package.json │ ├── package-lock.json │ └── index.js ├── api_server │ ├── package.json │ ├── index.js │ └── package-lock.json ├── cpu_opt │ ├── package.json │ ├── lib │ │ ├── md5.js │ │ └── v8_profiler.js │ ├── package-lock.json │ └── index.js ├── example │ ├── package.json │ ├── index.js │ ├── lib │ │ └── v8_profiler.js │ └── package-lock.json ├── network_io │ ├── package.json │ ├── lib │ │ ├── call_api.js │ │ └── v8_profiler.js │ └── index.js └── network_io_opt │ ├── package.json │ ├── lib │ ├── v8_profiler.js │ └── call_api.js │ └── index.js ├── 13 ├── src │ ├── config │ │ ├── products │ │ │ ├── c.json │ │ │ └── d.json │ │ └── b.json │ ├── middleware │ │ ├── logCenter.js │ │ ├── session.js │ │ └── security.js │ ├── controller │ │ ├── v1 │ │ │ ├── test.js │ │ │ ├── xss.js │ │ │ ├── eval.js │ │ │ └── sql.js │ │ ├── memLeak.js │ │ ├── content.js │ │ └── localCache.js │ ├── lib │ │ ├── singleton.js │ │ └── baseFun.js │ └── core │ │ ├── model.js │ │ ├── controller.js │ │ └── apiCenter.js ├── bin │ └── send_request.js ├── log │ └── test.log ├── package.json ├── app.js └── pm2.config.js ├── 14 ├── src │ ├── config │ │ ├── products │ │ │ ├── c.json │ │ │ └── d.json │ │ └── b.json │ ├── middleware │ │ ├── logCenter.js │ │ ├── session.js │ │ └── security.js │ ├── controller │ │ ├── v1 │ │ │ ├── test.js │ │ │ ├── xss.js │ │ │ ├── eval.js │ │ │ └── sql.js │ │ ├── memLeak.js │ │ ├── content.js │ │ └── localCache.js │ ├── lib │ │ ├── singleton.js │ │ └── baseFun.js │ └── core │ │ ├── model.js │ │ ├── controller.js │ │ └── apiCenter.js ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── log │ └── test.log ├── app.js ├── package.json └── pm2.config.js ├── 15 ├── src │ ├── config │ │ ├── products │ │ │ ├── c.json │ │ │ └── d.json │ │ └── b.json │ ├── middleware │ │ ├── logCenter.js │ │ ├── session.js │ │ └── security.js │ ├── controller │ │ ├── music │ │ │ └── info.js │ │ └── activity │ │ │ └── info.js │ ├── lib │ │ ├── singleton.js │ │ └── baseFun.js │ └── core │ │ ├── model.js │ │ ├── controller.js │ │ └── apiCenter.js ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── app.js ├── app-3003.js └── package.json ├── 16 ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── src │ ├── middleware │ │ ├── logCenter.js │ │ ├── session.js │ │ ├── security.js │ │ └── backendRouter.js │ ├── controller │ │ └── test.js │ ├── lib │ │ ├── nameService.js │ │ ├── apiCenter.js │ │ └── baseFun.js │ ├── core │ │ ├── model.js │ │ ├── apiCenter.js │ │ └── controller.js │ └── config │ │ └── lagou-nodejs.conf ├── app.js ├── app-3001.js └── package.json ├── 17 ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── src │ ├── middleware │ │ ├── logCenter.js │ │ ├── session.js │ │ ├── security.js │ │ └── backendRouter.js │ ├── lib │ │ ├── nameService.js │ │ ├── apiCenter.js │ │ └── baseFun.js │ ├── core │ │ ├── model.js │ │ ├── apiCenter.js │ │ └── controller.js │ ├── controller │ │ ├── act.js │ │ └── ticket.js │ └── config │ │ └── lagou-nodejs.conf ├── app-3001.js ├── app.js ├── package.json └── config │ └── lagou-nodejs.conf ├── 18 ├── src │ ├── model │ │ ├── user.js │ │ ├── ticket.js │ │ ├── history.js │ │ └── act.js │ ├── middleware │ │ ├── logCenter.js │ │ ├── security.js │ │ ├── backendRouter.js │ │ └── checkToken.js │ ├── core │ │ ├── service.js │ │ ├── apiCenter.js │ │ └── controller.js │ ├── lib │ │ ├── nameService.js │ │ ├── apiCenter.js │ │ ├── baseFun.js │ │ └── baseMongodb.js │ ├── service │ │ └── history.js │ └── config │ │ └── lagou-nodejs.conf ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── app.js ├── package.json ├── pm2.config.js └── config │ └── lagou-nodejs.conf ├── 19 ├── bin │ ├── send_request.js │ ├── post.lua │ └── post_tmp.lua ├── src │ ├── controller │ │ ├── index.js │ │ └── page.js │ ├── middleware │ │ ├── logCenter.js │ │ ├── security.js │ │ ├── backendRouter.js │ │ └── checkToken.js │ ├── core │ │ ├── service.js │ │ ├── apiCenter.js │ │ └── controller.js │ ├── lib │ │ ├── nameService.js │ │ ├── apiCenter.js │ │ ├── baseFun.js │ │ └── baseMongodb.js │ └── config │ │ └── lagou-nodejs.conf ├── package.json ├── app.js ├── pm2.config.js └── config │ └── lagou-nodejs.conf └── .gitignore /1/test.conf: -------------------------------------------------------------------------------- 1 | 1 -------------------------------------------------------------------------------- /1/config/test.conf: -------------------------------------------------------------------------------- 1 | test -------------------------------------------------------------------------------- /18/src/model/user.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /5/pm2/data/err-0.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /5/pm2/data/err-1.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /5/pm2/data/info-0.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /5/pm2/data/info-1.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /12/disk_io/test_file.conf: -------------------------------------------------------------------------------- 1 | test local file data -------------------------------------------------------------------------------- /12/disk_io_opt/test_file.conf: -------------------------------------------------------------------------------- 1 | test local file data -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .DS_Store 3 | .idea 4 | .clinic 5 | log -------------------------------------------------------------------------------- /13/src/config/products/c.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt", 3 | "sku" : "xxxx" 4 | } -------------------------------------------------------------------------------- /14/src/config/products/c.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt", 3 | "sku" : "xxxx" 4 | } -------------------------------------------------------------------------------- /15/src/config/products/c.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt", 3 | "sku" : "xxxx" 4 | } -------------------------------------------------------------------------------- /13/src/config/products/d.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt1", 3 | "sku" : "xxxx1" 4 | } -------------------------------------------------------------------------------- /14/src/config/products/d.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt1", 3 | "sku" : "xxxx1" 4 | } -------------------------------------------------------------------------------- /15/src/config/products/d.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "ttt1", 3 | "sku" : "xxxx1" 4 | } -------------------------------------------------------------------------------- /13/src/config/b.json: -------------------------------------------------------------------------------- 1 | { 2 | "database" : "xxx", 3 | "user" : "xx1", 4 | "passwd" : "xx2" 5 | } -------------------------------------------------------------------------------- /14/src/config/b.json: -------------------------------------------------------------------------------- 1 | { 2 | "database" : "xxx", 3 | "user" : "xx1", 4 | "passwd" : "xx2" 5 | } -------------------------------------------------------------------------------- /15/src/config/b.json: -------------------------------------------------------------------------------- 1 | { 2 | "database" : "xxx", 3 | "user" : "xx1", 4 | "passwd" : "xx2" 5 | } -------------------------------------------------------------------------------- /1/timer.js: -------------------------------------------------------------------------------- 1 | const fs = require(fs); 2 | 3 | setTimeout(() => { 4 | console.log('1'); 5 | }, 0); 6 | 7 | console.log('2'); -------------------------------------------------------------------------------- /12/cpu/lib/md5.js: -------------------------------------------------------------------------------- 1 | crypto = require('crypto'); 2 | 3 | module.exports = (content) => { 4 | return crypto.createHash('md5').update(content).digest("hex"); 5 | } -------------------------------------------------------------------------------- /11/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /13/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /14/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /15/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /16/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /17/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /18/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /19/bin/send_request.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../src/core/apiCenter'); 2 | 3 | for(let i=500; i<1000; i++){ 4 | ApiCenter.callApi(`http://127.0.0.1:3000/v1/test?username=${i}`); 5 | } -------------------------------------------------------------------------------- /14/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /14/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /15/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /15/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /16/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /16/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /17/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /17/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /18/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /18/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /19/bin/post.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "{post_str}" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /19/bin/post_tmp.lua: -------------------------------------------------------------------------------- 1 | -- example HTTP POST script which demonstrates setting the 2 | -- HTTP method, body, and adding a header 3 | 4 | wrk.method = "POST" 5 | wrk.body = "b=2" 6 | wrk.headers["Content-Type"] = "application/x-www-form-urlencoded" -------------------------------------------------------------------------------- /18/src/model/ticket.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class TicketModel extends Model { 4 | constructor(ctx) { 5 | super(ctx); 6 | this.collectionName = 'ticket'; 7 | } 8 | 9 | } 10 | 11 | module.exports = TicketModel; -------------------------------------------------------------------------------- /8/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | next(); 11 | } 12 | } -------------------------------------------------------------------------------- /10/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /11/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /13/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /14/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /15/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /9/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /15/src/controller/music/info.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../../core/controller'); 2 | 3 | class MusicInfo extends Controller { 4 | 5 | index() { 6 | return this.resApi(true, 'music info is good'); 7 | } 8 | 9 | 10 | } 11 | 12 | module.exports = MusicInfo; -------------------------------------------------------------------------------- /16/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /17/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /18/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /19/src/controller/index.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Index extends Controller { 4 | async index() { 5 | return this.resApi(true, 'success', 'nodejs cloumn default system'); 6 | } 7 | 8 | } 9 | 10 | module.exports = Index; -------------------------------------------------------------------------------- /19/src/middleware/logCenter.js: -------------------------------------------------------------------------------- 1 | const Log = require('../lib/log'); 2 | 3 | const log = new Log(); 4 | 5 | log.start(); 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | ctx.log = log; 10 | await next(); 11 | } 12 | } -------------------------------------------------------------------------------- /5/cluster/cluster.js: -------------------------------------------------------------------------------- 1 | const cluster = require('cluster'); 2 | const instances = 2; // 启动进程数量 3 | 4 | if (cluster.isMaster) { 5 | for(let i = 0;i{ 2 | console.log('timer1') 3 | Promise.resolve().then(function() { 4 | console.log('promise1') 5 | }) 6 | }, 0) 7 | setTimeout(()=>{ 8 | console.log('timer2') 9 | Promise.resolve().then(function() { 10 | console.log('promise2') 11 | }) 12 | }, 0) 13 | -------------------------------------------------------------------------------- /12/api_server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "v8-profiler-next": "^1.3.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /12/cpu_opt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "v8-profiler-next": "^1.3.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /12/disk_io/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "v8-profiler-next": "^1.3.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /12/example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "v8-profiler-next": "^1.3.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /12/disk_io_opt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "v8-profiler-next": "^1.3.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /8/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const app = new Koa(); 3 | const routerMiddleware = require('./src/middleware/router'); 4 | const logCenter = require('./src/middleware/logCenter'); 5 | 6 | app.use(logCenter()); 7 | app.use(routerMiddleware()); 8 | 9 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /11/src/controller/v1/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | index() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | indexTest() { 10 | return this.resApi(true, 'good 2'); 11 | } 12 | 13 | } 14 | 15 | module.exports = Test; -------------------------------------------------------------------------------- /13/src/controller/v1/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | index() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | indexTest() { 10 | return this.resApi(true, 'good 2'); 11 | } 12 | 13 | } 14 | 15 | module.exports = Test; -------------------------------------------------------------------------------- /14/src/controller/v1/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | index() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | indexTest() { 10 | return this.resApi(true, 'good 2'); 11 | } 12 | 13 | } 14 | 15 | module.exports = Test; -------------------------------------------------------------------------------- /10/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const app = new Koa(); 3 | const routerMiddleware = require('./src/middleware/router'); 4 | const logCenter = require('./src/middleware/logCenter'); 5 | 6 | app.use(logCenter()); 7 | app.use(routerMiddleware()); 8 | 9 | 10 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /4/express/myapp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "myapp", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "express": "^4.17.1" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /9/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const app = new Koa(); 3 | const routerMiddleware = require('./src/middleware/router'); 4 | const logCenter = require('./src/middleware/logCenter'); 5 | 6 | app.use(logCenter()); 7 | app.use(routerMiddleware()); 8 | 9 | 10 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /4/koa/myapp-async/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "myapp-async", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "koa": "^2.13.0" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /11/src/controller/memLeak.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class MemLeak extends Controller { 4 | 5 | login() { 6 | for(let i=0; i<10000000; i++){ 7 | this.ctx.session.set(i); 8 | } 9 | return this.resApi(true, 'set success'); 10 | } 11 | } 12 | 13 | module.exports = MemLeak; -------------------------------------------------------------------------------- /12/network_io/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "request": "^2.88.2", 13 | "v8-profiler-next": "^1.3.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /12/network_io_opt/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "request": "^2.88.2", 13 | "v8-profiler-next": "^1.3.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /13/src/controller/memLeak.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class MemLeak extends Controller { 4 | 5 | login() { 6 | for(let i=0; i<10000000; i++){ 7 | this.ctx.session.set(i); 8 | } 9 | return this.resApi(true, 'set success'); 10 | } 11 | } 12 | 13 | module.exports = MemLeak; -------------------------------------------------------------------------------- /14/src/controller/memLeak.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class MemLeak extends Controller { 4 | 5 | login() { 6 | for(let i=0; i<10000000; i++){ 7 | this.ctx.session.set(i); 8 | } 9 | return this.resApi(true, 'set success'); 10 | } 11 | } 12 | 13 | module.exports = MemLeak; -------------------------------------------------------------------------------- /4/express/myapp-async/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "myapp-async", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "express": "^4.17.1" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /5/pm2/app.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | res.write('hello world, start with pm2'); 8 | res.end(); 9 | }); 10 | 11 | /** 12 | * 13 | * 启动服务 14 | */ 15 | server.listen(3000, () => { 16 | console.log('server start http://127.0.0.1:3000'); 17 | }); -------------------------------------------------------------------------------- /12/cpu_opt/lib/md5.js: -------------------------------------------------------------------------------- 1 | crypto = require('crypto'); 2 | 3 | // 保存缓存信息 4 | const md5Cache = {}; 5 | 6 | module.exports = (content) => { 7 | if(md5Cache[content]) { // 判断是否存在缓存信息,存在则直接返回 8 | return md5Cache[content] 9 | } 10 | /** 不存在则计算并返回 */ 11 | md5Cache[content] = crypto.createHash('md5').update(content).digest("hex"); 12 | return md5Cache[content]; 13 | } -------------------------------------------------------------------------------- /3/api-server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "directories": { 7 | "lib": "lib" 8 | }, 9 | "scripts": { 10 | "test": "echo \"Error: no test specified\" && exit 1" 11 | }, 12 | "author": "", 13 | "license": "ISC", 14 | "dependencies": { 15 | "mongodb": "^3.6.3" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /3/msvc/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "msvc", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "mongodb": "^3.6.3", 11 | "request": "^2.88.2", 12 | "request-promise": "^4.2.6" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /3/mvc/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mvc", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "mongodb": "^3.6.3", 11 | "request": "^2.88.2", 12 | "request-promise": "^4.2.6" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /10/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | } 14 | 15 | module.exports = Content; -------------------------------------------------------------------------------- /6/api/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-test", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "mongodb": "^3.6.3", 11 | "request": "^2.88.2", 12 | "request-promise": "^4.2.6" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /6/cpu/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cpu-test", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "mongodb": "^3.6.3", 11 | "request": "^2.88.2", 12 | "request-promise": "^4.2.6" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /6/io/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "io-test", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "mongodb": "^3.6.3", 11 | "request": "^2.88.2", 12 | "request-promise": "^4.2.6" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /8/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | } 14 | 15 | module.exports = Content; -------------------------------------------------------------------------------- /9/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | } 14 | 15 | module.exports = Content; -------------------------------------------------------------------------------- /11/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | 14 | } 15 | 16 | module.exports = Content; -------------------------------------------------------------------------------- /13/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | 14 | } 15 | 16 | module.exports = Content; -------------------------------------------------------------------------------- /14/src/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Content extends Controller { 4 | 5 | test() { 6 | return this.resApi(true, 'good'); 7 | } 8 | 9 | log() { 10 | this.ctx.log.info('test', `good success ${Math.random()}`) 11 | return this.resApi(true, 'log success'); 12 | } 13 | 14 | } 15 | 16 | module.exports = Content; -------------------------------------------------------------------------------- /8/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "koa": "^2.13.1", 13 | "redis": "^3.0.2", 14 | "node-cache": "^5.1.2", 15 | "util": "^0.12.3" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /9/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "koa": "^2.13.1", 13 | "node-cache": "^5.1.2", 14 | "redis": "^3.0.2", 15 | "util": "^0.12.3" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /10/src/lib/singleton.js: -------------------------------------------------------------------------------- 1 | let singleton; 2 | 3 | const userList = []; 4 | class Singleton { 5 | add(uid) { 6 | userList.push(uid); 7 | } 8 | 9 | getLength() { 10 | return userList.length; 11 | } 12 | } 13 | 14 | module.exports = () => { 15 | if(singleton){ 16 | return singleton; 17 | } 18 | 19 | singleton = new Singleton(); 20 | return singleton; 21 | } -------------------------------------------------------------------------------- /11/src/lib/singleton.js: -------------------------------------------------------------------------------- 1 | let singleton; 2 | 3 | const userList = []; 4 | class Singleton { 5 | add(uid) { 6 | userList.push(uid); 7 | } 8 | 9 | getLength() { 10 | return userList.length; 11 | } 12 | } 13 | 14 | module.exports = () => { 15 | if(singleton){ 16 | return singleton; 17 | } 18 | 19 | singleton = new Singleton(); 20 | return singleton; 21 | } -------------------------------------------------------------------------------- /13/src/lib/singleton.js: -------------------------------------------------------------------------------- 1 | let singleton; 2 | 3 | const userList = []; 4 | class Singleton { 5 | add(uid) { 6 | userList.push(uid); 7 | } 8 | 9 | getLength() { 10 | return userList.length; 11 | } 12 | } 13 | 14 | module.exports = () => { 15 | if(singleton){ 16 | return singleton; 17 | } 18 | 19 | singleton = new Singleton(); 20 | return singleton; 21 | } -------------------------------------------------------------------------------- /14/src/lib/singleton.js: -------------------------------------------------------------------------------- 1 | let singleton; 2 | 3 | const userList = []; 4 | class Singleton { 5 | add(uid) { 6 | userList.push(uid); 7 | } 8 | 9 | getLength() { 10 | return userList.length; 11 | } 12 | } 13 | 14 | module.exports = () => { 15 | if(singleton){ 16 | return singleton; 17 | } 18 | 19 | singleton = new Singleton(); 20 | return singleton; 21 | } -------------------------------------------------------------------------------- /15/src/lib/singleton.js: -------------------------------------------------------------------------------- 1 | let singleton; 2 | 3 | const userList = []; 4 | class Singleton { 5 | add(uid) { 6 | userList.push(uid); 7 | } 8 | 9 | getLength() { 10 | return userList.length; 11 | } 12 | } 13 | 14 | module.exports = () => { 15 | if(singleton){ 16 | return singleton; 17 | } 18 | 19 | singleton = new Singleton(); 20 | return singleton; 21 | } -------------------------------------------------------------------------------- /7/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "msvc", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "current-processes": "^0.2.1", 11 | "mongodb": "^3.6.3", 12 | "request": "^2.88.2", 13 | "request-promise": "^4.2.6" 14 | }, 15 | "author": "", 16 | "license": "ISC" 17 | } 18 | -------------------------------------------------------------------------------- /10/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "koa": "^2.13.1", 13 | "lodash": "^4.17.21", 14 | "node-cache": "^5.1.2", 15 | "redis": "^3.0.2", 16 | "util": "^0.12.3" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /5/cluster/app.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | res.write(`hello world, start with cluster ${process.pid}`); 8 | res.end(); 9 | }); 10 | /** 11 | * 12 | * 启动服务 13 | */ 14 | server.listen(3000, () => { 15 | console.log('server start http://127.0.0.1:3000'); 16 | }); 17 | 18 | console.log(`Worker ${process.pid} started`); -------------------------------------------------------------------------------- /11/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /13/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /14/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /15/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /16/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /17/src/middleware/session.js: -------------------------------------------------------------------------------- 1 | const loginUsers = {}; 2 | 3 | module.exports = function () { 4 | return async function ( ctx, next ) { 5 | ctx.session = session; 6 | await next(); 7 | } 8 | } 9 | 10 | const session = { 11 | set: function(username) { 12 | loginUsers[username] = true; 13 | }, 14 | 15 | check: function(username){ 16 | return loginUsers[username] ? true : false; 17 | } 18 | }; -------------------------------------------------------------------------------- /12/api_server/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | setTimeout(() => { // 延迟 1 秒返回 8 | res.write('this is api result'); 9 | res.end(); 10 | }, 1 * 1000); 11 | }); 12 | /** 13 | * 14 | * 启动服务,并开始执行 v8 profiler 的采集工作 15 | */ 16 | server.listen(4000, () => { 17 | console.log('server start http://127.0.0.1:4000'); 18 | }); -------------------------------------------------------------------------------- /1/poll.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | setTimeout(() => { // 新的事件循环的起点 4 | console.log('1'); 5 | }, 0); 6 | 7 | /// 回调将会在新的事件循环之前 8 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 9 | if (err) throw err; 10 | console.log('read file success'); 11 | }); 12 | 13 | /// 该部分将会在首次事件循环中执行 14 | Promise.resolve().then(()=>{ 15 | console.log('poll callback'); 16 | }); 17 | 18 | // 首次事件循环执行 19 | console.log('2'); 20 | -------------------------------------------------------------------------------- /1/practice/startServer.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | let sum = 0; 8 | for(let i=0; i<500000000; i++){ 9 | sum = sum + i; 10 | } 11 | res.write(`${sum}`); 12 | res.end(); 13 | }); 14 | 15 | /** 16 | * 17 | * 启动服务 18 | */ 19 | server.listen(5000, () => { 20 | console.log('server start http://127.0.0.1:5000'); 21 | }); -------------------------------------------------------------------------------- /3/restful/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "restful", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "directories": { 7 | "lib": "lib" 8 | }, 9 | "scripts": { 10 | "test": "echo \"Error: no test specified\" && exit 1" 11 | }, 12 | "author": "", 13 | "license": "ISC", 14 | "dependencies": { 15 | "mongodb": "^3.6.3", 16 | "request": "^2.88.2", 17 | "request-promise": "^4.2.6" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /1/practice/nextServer.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | let sum = 0; 8 | for(let i=500000000; i<1000000000; i++){ 9 | sum = sum + i; 10 | } 11 | res.write(`${sum}`); 12 | res.end(); 13 | }); 14 | 15 | /** 16 | * 17 | * 启动服务 18 | */ 19 | server.listen(6000, () => { 20 | console.log('server start http://127.0.0.1:6000'); 21 | }); -------------------------------------------------------------------------------- /7/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /10/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /11/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /13/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /14/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /15/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /3/mvc/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /6/api/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /6/cpu/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /6/io/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /8/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /9/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | } 15 | 16 | module.exports = Model; -------------------------------------------------------------------------------- /18/src/core/service.js: -------------------------------------------------------------------------------- 1 | class Service { 2 | constructor(ctx) { 3 | this.ctx = ctx; 4 | } 5 | 6 | /** 7 | * 8 | * @param {string} logType 日志类型 info | error | warning | debug 9 | * @param {string} message 消息 10 | * @param {object} logInfo 日志信息 11 | */ 12 | log(logType, message, logInfo) { 13 | return this.ctx.log.add(logType, this.ctx.pathname, message, logInfo); 14 | } 15 | } 16 | 17 | module.exports = Service; -------------------------------------------------------------------------------- /19/src/core/service.js: -------------------------------------------------------------------------------- 1 | class Service { 2 | constructor(ctx) { 3 | this.ctx = ctx; 4 | } 5 | 6 | /** 7 | * 8 | * @param {string} logType 日志类型 info | error | warning | debug 9 | * @param {string} message 消息 10 | * @param {object} logInfo 日志信息 11 | */ 12 | log(logType, message, logInfo) { 13 | return this.ctx.log.add(logType, this.ctx.pathname, message, logInfo); 14 | } 15 | } 16 | 17 | module.exports = Service; -------------------------------------------------------------------------------- /10/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /11/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /12/example/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | // 引入 v8-profiler 库,可以作为一个中间件来实现 3 | const v8Profiler = require('./lib/v8_profiler'); 4 | /** 5 | * 6 | * 创建 http 服务,简单返回 7 | */ 8 | const server = http.createServer((req, res) => { 9 | res.write('Node.js'); 10 | res.end(); 11 | }); 12 | /** 13 | * 14 | * 启动服务,并开始执行 v8 profiler 的采集工作 15 | */ 16 | server.listen(3000, () => { 17 | console.log('server start http://127.0.0.1:3000'); 18 | v8Profiler.start(); 19 | }); -------------------------------------------------------------------------------- /13/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /13/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /14/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /14/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /15/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /16/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /17/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /18/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /19/src/middleware/security.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | const whiteList = [ 4 | '127.0.0.1:3000' 5 | ]; 6 | 7 | module.exports = function () { 8 | return async function ( ctx, next ) { 9 | if(ctx.request.headers.referer && !whiteList.includes(ctx.request.headers.referer)){ 10 | baseFun.setResInfo(ctx, false, 'access have been forbidden', null, 403); 11 | return; 12 | } 13 | return await next(); 14 | } 15 | } -------------------------------------------------------------------------------- /8/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /9/log/test.log: -------------------------------------------------------------------------------- 1 | good success 0.4400041351511781 2 | good success 0.8533540410020264 3 | good success 0.05602191887030328 4 | good success 0.9211995961759676 5 | good success 0.18125957486134014 6 | good success 0.6596932504127817 7 | good success 0.3795250689874936 8 | good success 0.6604535687333575 9 | good success 0.18576856682615417 10 | good success 0.0902864116575044 11 | good success 0.08187170753204853 12 | good success 0.40825663747040863 13 | good success 0.6818250998149147 14 | -------------------------------------------------------------------------------- /13/src/controller/v1/xss.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const Controller = require('../../core/controller'); 4 | 5 | class Xss extends Controller { 6 | 7 | index() { 8 | const params = querystring.parse(this.ctx.request.querystring); 9 | 10 | let name = decodeURI(params['name']); 11 | 12 | return this.ctx.response.body = name; 13 | //return this.resApi(true, 'good', a); 14 | } 15 | 16 | } 17 | 18 | module.exports = Xss; -------------------------------------------------------------------------------- /14/src/controller/v1/xss.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const Controller = require('../../core/controller'); 4 | 5 | class Xss extends Controller { 6 | 7 | index() { 8 | const params = querystring.parse(this.ctx.request.querystring); 9 | 10 | let name = decodeURI(params['name']); 11 | 12 | return this.ctx.response.body = name; 13 | //return this.resApi(true, 'good', a); 14 | } 15 | 16 | } 17 | 18 | module.exports = Xss; -------------------------------------------------------------------------------- /16/src/controller/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | index() { 6 | this.log('info', 'test'); 7 | this.log('error', {'a':1, 'b':2}); 8 | this.log('warning', 'warning'); 9 | this.log('debug', 'warning'); 10 | return this.resApi(true, 'good'); 11 | } 12 | 13 | indexTest() { 14 | return this.resApi(true, 'good 2'); 15 | } 16 | 17 | } 18 | 19 | module.exports = Test; -------------------------------------------------------------------------------- /12/network_io/lib/call_api.js: -------------------------------------------------------------------------------- 1 | // 引入 request 库,需要在 package.json 中申明,并且 npm install 2 | const request = require('request'); 3 | 4 | /** 5 | * 6 | * request 调用外部 api 7 | * @param {*} apiLink string 8 | * @param {*} callback funtion 9 | * 10 | */ 11 | module.exports = (apiLink, callback) => { 12 | request(apiLink, function (error, response, body) { 13 | if(error) { 14 | callback(false); 15 | } else { 16 | callback(body); 17 | } 18 | }); 19 | } -------------------------------------------------------------------------------- /7/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /3/msvc/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /3/mvc/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /6/api/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /6/cpu/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /6/io/model/content.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class ContenModel extends Model { 4 | constructor() { 5 | super(); 6 | this.collectionName = 'content'; 7 | } 8 | 9 | async getList() { 10 | const queryOption = {}; 11 | const collection = await this.get(this.collectionName); 12 | const queryArr = await collection.find(queryOption).toArray(); 13 | 14 | return queryArr; 15 | } 16 | } 17 | 18 | module.exports = ContenModel; -------------------------------------------------------------------------------- /16/src/lib/nameService.js: -------------------------------------------------------------------------------- 1 | const serviceMapping = { 2 | 'poxyBackendServer' : [ 3 | '127.0.0.1:3002', 4 | '127.0.0.1:3003', 5 | ] 6 | }; 7 | class NameService { 8 | static get(name) { 9 | if(!serviceMapping[name] || serviceMapping[name].length < 1){ 10 | return false; 11 | } 12 | const serviceList = serviceMapping[name]; 13 | return serviceList[Math.floor(Math.random()*serviceList.length)]; 14 | } 15 | } 16 | 17 | module.exports = NameService; -------------------------------------------------------------------------------- /17/src/lib/nameService.js: -------------------------------------------------------------------------------- 1 | const serviceMapping = { 2 | 'poxyBackendServer' : [ 3 | '127.0.0.1:3002', 4 | '127.0.0.1:3003', 5 | ] 6 | }; 7 | class NameService { 8 | static get(name) { 9 | if(!serviceMapping[name] || serviceMapping[name].length < 1){ 10 | return false; 11 | } 12 | const serviceList = serviceMapping[name]; 13 | return serviceList[Math.floor(Math.random()*serviceList.length)]; 14 | } 15 | } 16 | 17 | module.exports = NameService; -------------------------------------------------------------------------------- /18/src/lib/nameService.js: -------------------------------------------------------------------------------- 1 | const serviceMapping = { 2 | 'poxyBackendServer' : [ 3 | '127.0.0.1:3002', 4 | '127.0.0.1:3003', 5 | ] 6 | }; 7 | class NameService { 8 | static get(name) { 9 | if(!serviceMapping[name] || serviceMapping[name].length < 1){ 10 | return false; 11 | } 12 | const serviceList = serviceMapping[name]; 13 | return serviceList[Math.floor(Math.random()*serviceList.length)]; 14 | } 15 | } 16 | 17 | module.exports = NameService; -------------------------------------------------------------------------------- /19/src/lib/nameService.js: -------------------------------------------------------------------------------- 1 | const serviceMapping = { 2 | 'poxyBackendServer' : [ 3 | '127.0.0.1:3002', 4 | '127.0.0.1:3003', 5 | ] 6 | }; 7 | class NameService { 8 | static get(name) { 9 | if(!serviceMapping[name] || serviceMapping[name].length < 1){ 10 | return false; 11 | } 12 | const serviceList = serviceMapping[name]; 13 | return serviceList[Math.floor(Math.random()*serviceList.length)]; 14 | } 15 | } 16 | 17 | module.exports = NameService; -------------------------------------------------------------------------------- /11/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "heapdump": "^0.3.15", 13 | "koa": "^2.13.1", 14 | "lodash": "^4.17.21", 15 | "node-cache": "^5.1.2", 16 | "redis": "^3.0.2", 17 | "request": "^2.88.2", 18 | "request-promise": "^4.2.6", 19 | "util": "^0.12.3" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /18/src/model/history.js: -------------------------------------------------------------------------------- 1 | const Model = require('../core/model'); 2 | 3 | class HistoryModel extends Model { 4 | constructor(ctx) { 5 | super(ctx); 6 | this.collectionName = 'ticket_history'; 7 | } 8 | 9 | async getMyTickList(page=0, pageSize=20) { 10 | const queryOption = { 11 | 'user_id' : this.ctx.userId 12 | }; 13 | return await this.getList(queryOption, {'start_time':-1, 'is_effective':1}, pageSize, page*pageSize); 14 | } 15 | 16 | } 17 | 18 | module.exports = HistoryModel; -------------------------------------------------------------------------------- /1/setImmediate.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | setTimeout(() => { // 新的事件循环的起点 4 | console.log('1'); 5 | }, 0); 6 | 7 | setImmediate( () => { 8 | console.log('setImmediate 1'); 9 | }); 10 | 11 | /// 将会在 poll 阶段执行 12 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 13 | if (err) throw err; 14 | console.log('read file success'); 15 | }); 16 | 17 | /// 该部分将会在首次事件循环中执行 18 | Promise.resolve().then(()=>{ 19 | console.log('poll callback'); 20 | }); 21 | 22 | 23 | // 首次事件循环执行 24 | console.log('2'); 25 | -------------------------------------------------------------------------------- /12/disk_io/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const fs = require('fs'); 3 | // 引入 v8-profiler 库,可以作为一个中间件来实现 4 | const v8Profiler = require('./lib/v8_profiler'); 5 | /** 6 | * 7 | * 创建 http 服务,简单返回 8 | */ 9 | const server = http.createServer((req, res) => { 10 | let ret = fs.readFileSync('./test_file.conf'); 11 | res.write(ret); 12 | res.end(); 13 | }); 14 | /** 15 | * 16 | * 启动服务,并开始执行 v8 profiler 的采集工作 17 | */ 18 | server.listen(3000, () => { 19 | console.log('server start http://127.0.0.1:3000'); 20 | v8Profiler.start(); 21 | }); -------------------------------------------------------------------------------- /13/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "heapdump": "^0.3.15", 13 | "koa": "^2.13.1", 14 | "koa-body": "^4.2.0", 15 | "lodash": "^4.17.21", 16 | "node-cache": "^5.1.2", 17 | "redis": "^3.0.2", 18 | "request": "^2.88.2", 19 | "request-promise": "^4.2.6", 20 | "util": "^0.12.3" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /13/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const logCenter = require('./src/middleware/logCenter'); 7 | const security = require('./src/middleware/security'); 8 | const session = require('./src/middleware/session'); 9 | 10 | app.use(logCenter()); 11 | app.use(session()); 12 | app.use(security()); 13 | app.use(koaBody({ 14 | multipart: true 15 | })); 16 | app.use(routerMiddleware()); 17 | 18 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /14/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const logCenter = require('./src/middleware/logCenter'); 7 | const security = require('./src/middleware/security'); 8 | const session = require('./src/middleware/session'); 9 | 10 | app.use(logCenter()); 11 | app.use(session()); 12 | app.use(security()); 13 | app.use(koaBody({ 14 | multipart: true 15 | })); 16 | app.use(routerMiddleware()); 17 | 18 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /15/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const logCenter = require('./src/middleware/logCenter'); 7 | const security = require('./src/middleware/security'); 8 | const session = require('./src/middleware/session'); 9 | 10 | app.use(logCenter()); 11 | app.use(session()); 12 | app.use(security()); 13 | app.use(koaBody({ 14 | multipart: true 15 | })); 16 | app.use(routerMiddleware()); 17 | 18 | app.listen(3002, () => console.log(`Example app listening on port 3002!`)); -------------------------------------------------------------------------------- /15/app-3003.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const logCenter = require('./src/middleware/logCenter'); 7 | const security = require('./src/middleware/security'); 8 | const session = require('./src/middleware/session'); 9 | 10 | app.use(logCenter()); 11 | app.use(session()); 12 | app.use(security()); 13 | app.use(koaBody({ 14 | multipart: true 15 | })); 16 | app.use(routerMiddleware()); 17 | 18 | app.listen(3003, () => console.log(`Example app listening on port 3003!`)); -------------------------------------------------------------------------------- /16/src/middleware/backendRouter.js: -------------------------------------------------------------------------------- 1 | const proxy = require('koa-better-http-proxy'); 2 | const nameService = require('../lib/nameService'); 3 | 4 | module.exports = function () { 5 | return function ( ctx, next ) { 6 | if(ctx.currentExist){ 7 | return; 8 | } 9 | 10 | /// 转发相应的数据到指定服务,并且记录下系统日志 11 | const newService = nameService.get('poxyBackendServer'); 12 | ctx.log.add('info', 'system', `current server do not find the ${ctx.pathname} path, forward the request to ${newService}`); 13 | 14 | return proxy(newService)(ctx, next); 15 | } 16 | } -------------------------------------------------------------------------------- /17/src/middleware/backendRouter.js: -------------------------------------------------------------------------------- 1 | const proxy = require('koa-better-http-proxy'); 2 | const nameService = require('../lib/nameService'); 3 | 4 | module.exports = function () { 5 | return function ( ctx, next ) { 6 | if(ctx.currentExist){ 7 | return; 8 | } 9 | 10 | /// 转发相应的数据到指定服务,并且记录下系统日志 11 | const newService = nameService.get('poxyBackendServer'); 12 | ctx.log.add('info', 'system', `current server do not find the ${ctx.pathname} path, forward the request to ${newService}`); 13 | 14 | return proxy(newService)(ctx, next); 15 | } 16 | } -------------------------------------------------------------------------------- /18/src/middleware/backendRouter.js: -------------------------------------------------------------------------------- 1 | const proxy = require('koa-better-http-proxy'); 2 | const nameService = require('../lib/nameService'); 3 | 4 | module.exports = function () { 5 | return function ( ctx, next ) { 6 | if(ctx.currentExist){ 7 | return; 8 | } 9 | 10 | /// 转发相应的数据到指定服务,并且记录下系统日志 11 | const newService = nameService.get('poxyBackendServer'); 12 | ctx.log.add('info', 'system', `current server do not find the ${ctx.pathname} path, forward the request to ${newService}`); 13 | 14 | return proxy(newService)(ctx, next); 15 | } 16 | } -------------------------------------------------------------------------------- /19/src/middleware/backendRouter.js: -------------------------------------------------------------------------------- 1 | const proxy = require('koa-better-http-proxy'); 2 | const nameService = require('../lib/nameService'); 3 | 4 | module.exports = function () { 5 | return function ( ctx, next ) { 6 | if(ctx.currentExist){ 7 | return; 8 | } 9 | 10 | /// 转发相应的数据到指定服务,并且记录下系统日志 11 | const newService = nameService.get('poxyBackendServer'); 12 | ctx.log.add('info', 'system', `current server do not find the ${ctx.pathname} path, forward the request to ${newService}`); 13 | 14 | return proxy(newService)(ctx, next); 15 | } 16 | } -------------------------------------------------------------------------------- /10/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /11/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /13/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /14/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /15/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /16/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const backendRouter = require('./src/middleware/backendRouter'); 7 | const logCenter = require('./src/middleware/logCenter'); 8 | const security = require('./src/middleware/security'); 9 | 10 | app.use(logCenter()); 11 | app.use(security()); 12 | app.use(koaBody({ 13 | multipart: true 14 | })); 15 | app.use(routerMiddleware()); 16 | app.use(backendRouter()); 17 | 18 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /8/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /9/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | } 21 | 22 | module.exports = Controller; -------------------------------------------------------------------------------- /1/queue.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | // 首次事件循环执行 3 | console.log('start'); 4 | 5 | /// 将会在新的事件循环中的阶段执行 6 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 7 | if (err) throw err; 8 | console.log('read file success'); 9 | }); 10 | 11 | setTimeout(() => { // 新的事件循环的起点 12 | console.log('setTimeout'); 13 | }, 0); 14 | 15 | /// 该部分将会在首次事件循环中执行 16 | Promise.resolve().then(()=>{ 17 | console.log('Promise callback'); 18 | }); 19 | 20 | /// 执行 process.nextTick 21 | process.nextTick(() => { 22 | console.log('nextTick callback'); 23 | }); 24 | 25 | // 首次事件循环执行 26 | console.log('end'); 27 | -------------------------------------------------------------------------------- /16/app-3001.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const backendRouter = require('./src/middleware/backendRouter'); 7 | const logCenter = require('./src/middleware/logCenter'); 8 | const security = require('./src/middleware/security'); 9 | 10 | app.use(logCenter()); 11 | app.use(security()); 12 | app.use(koaBody({ 13 | multipart: true 14 | })); 15 | app.use(routerMiddleware()); 16 | app.use(backendRouter()); 17 | 18 | app.listen(3001, () => console.log(`Example app listening on port 3001!`)); -------------------------------------------------------------------------------- /17/app-3001.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | const backendRouter = require('./src/middleware/backendRouter'); 7 | const logCenter = require('./src/middleware/logCenter'); 8 | const security = require('./src/middleware/security'); 9 | 10 | app.use(logCenter()); 11 | app.use(security()); 12 | app.use(koaBody({ 13 | multipart: true 14 | })); 15 | app.use(routerMiddleware()); 16 | app.use(backendRouter()); 17 | 18 | app.listen(3001, () => console.log(`Example app listening on port 3001!`)); -------------------------------------------------------------------------------- /17/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const routerMiddleware = require('./src/middleware/router'); 6 | //const backendRouter = require('./src/middleware/backendRouter'); 7 | const logCenter = require('./src/middleware/logCenter'); 8 | const security = require('./src/middleware/security'); 9 | 10 | app.use(logCenter()); 11 | app.use(security()); 12 | app.use(koaBody({ 13 | multipart: true 14 | })); 15 | app.use(routerMiddleware()); 16 | //app.use(backendRouter()); 17 | 18 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /1/callback.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | setTimeout(() => { // 新的事件循环的起点 4 | console.log('1'); 5 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 6 | if (err) throw err; 7 | console.log('read file sync success'); 8 | }); 9 | }, 0); 10 | 11 | /// 回调将会在新的事件循环之前 12 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 13 | if (err) throw err; 14 | console.log('read file success'); 15 | }); 16 | 17 | /// 该部分将会在首次事件循环中执行 18 | Promise.resolve().then(()=>{ 19 | console.log('poll callback'); 20 | }); 21 | 22 | // 首次事件循环执行 23 | console.log('2'); 24 | -------------------------------------------------------------------------------- /6/api/controller/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | constructor(res, req) { 6 | super(res, req); 7 | } 8 | /** 9 | * 复杂运算 10 | */ 11 | bad() { 12 | let sum = 0; 13 | for(let i=0; i<10000000000; i++){ 14 | sum = sum + i; 15 | } 16 | 17 | return this.resApi(true, 'success', {'sum' : sum}); 18 | } 19 | 20 | /** 21 | * 正常请求 22 | */ 23 | normal() { 24 | return this.resApi(true, 'good', 'hello world'); 25 | } 26 | } 27 | 28 | module.exports = Test; -------------------------------------------------------------------------------- /6/cpu/controller/test.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Test extends Controller { 4 | 5 | constructor(res, req) { 6 | super(res, req); 7 | } 8 | /** 9 | * 复杂运算 10 | */ 11 | bad() { 12 | let sum = 0; 13 | for(let i=0; i<10000000000; i++){ 14 | sum = sum + i; 15 | } 16 | 17 | return this.resApi(true, 'success', {'sum' : sum}); 18 | } 19 | 20 | /** 21 | * 正常请求 22 | */ 23 | normal() { 24 | return this.resApi(true, 'good', 'hello world'); 25 | } 26 | } 27 | 28 | module.exports = Test; -------------------------------------------------------------------------------- /13/src/controller/v1/eval.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | const Controller = require('../../core/controller'); 3 | 4 | class Eval extends Controller { 5 | 6 | index() { 7 | const params = querystring.parse(this.ctx.request.querystring); 8 | // 获取参数 r 9 | let r = decodeURI(params['r']); 10 | // 根据参数 r 动态调用 this._p() 获取执行结果 11 | let ret = eval(`this._q() + ${r}`); 12 | 13 | return this.resApi(true, 'good', ret); 14 | } 15 | 16 | _q () { 17 | return 1; 18 | } 19 | 20 | _p () { 21 | return 2; 22 | } 23 | 24 | } 25 | 26 | module.exports = Eval; -------------------------------------------------------------------------------- /14/src/controller/v1/eval.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | const Controller = require('../../core/controller'); 3 | 4 | class Eval extends Controller { 5 | 6 | index() { 7 | const params = querystring.parse(this.ctx.request.querystring); 8 | // 获取参数 r 9 | let r = decodeURI(params['r']); 10 | // 根据参数 r 动态调用 this._p() 获取执行结果 11 | let ret = eval(`this._q() + ${r}`); 12 | 13 | return this.resApi(true, 'good', ret); 14 | } 15 | 16 | _q () { 17 | return 1; 18 | } 19 | 20 | _p () { 21 | return 2; 22 | } 23 | 24 | } 25 | 26 | module.exports = Eval; -------------------------------------------------------------------------------- /1/block.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | setTimeout(() => { // 新的事件循环的起点 4 | console.log('1'); 5 | sleep(10000) 6 | console.log('sleep 10s'); 7 | }, 0); 8 | 9 | /// 将会在 poll 阶段执行 10 | fs.readFile('./config/test.conf', {encoding: 'utf-8'}, (err, data) => { 11 | if (err) throw err; 12 | console.log('read file success'); 13 | }); 14 | 15 | console.log('2'); 16 | 17 | /// 函数实现,参数 n 单位 毫秒 ; 18 | function sleep ( n ) { 19 | var start = new Date().getTime() ; 20 | while ( true ) { 21 | if ( new Date().getTime() - start > n ) { 22 | // 使用 break 实现; 23 | break; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /6/io/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../util/baseFun'); 2 | 3 | class Controller { 4 | constructor(res, req) { 5 | this.res = res; 6 | this.req = req; 7 | } 8 | 9 | /** 10 | * 11 | * @description 设置响应数据 12 | * @param object res http res 13 | * @param boolean ret boolean 14 | * @param string message string 15 | * @param object dataInfo object 16 | * @param int httpStatus 17 | */ 18 | resApi(ret, message, dataInfo, httpStatus=200) { 19 | return baseFun.setResInfo(this.res, ret, message, dataInfo, httpStatus); 20 | } 21 | } 22 | 23 | module.exports = Controller; -------------------------------------------------------------------------------- /7/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../util/baseFun'); 2 | 3 | class Controller { 4 | constructor(res, req) { 5 | this.res = res; 6 | this.req = req; 7 | } 8 | 9 | /** 10 | * 11 | * @description 设置响应数据 12 | * @param object res http res 13 | * @param boolean ret boolean 14 | * @param string message string 15 | * @param object dataInfo object 16 | * @param int httpStatus 17 | */ 18 | resApi(ret, message, dataInfo, httpStatus=200) { 19 | return baseFun.setResInfo(this.res, ret, message, dataInfo, httpStatus); 20 | } 21 | } 22 | 23 | module.exports = Controller; -------------------------------------------------------------------------------- /3/mvc/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../util/baseFun'); 2 | 3 | class Controller { 4 | constructor(res, req) { 5 | this.res = res; 6 | this.req = req; 7 | } 8 | 9 | /** 10 | * 11 | * @description 设置响应数据 12 | * @param object res http res 13 | * @param boolean ret boolean 14 | * @param string message string 15 | * @param object dataInfo object 16 | * @param int httpStatus 17 | */ 18 | resApi(ret, message, dataInfo, httpStatus=200) { 19 | return baseFun.setResInfo(this.res, ret, message, dataInfo, httpStatus); 20 | } 21 | } 22 | 23 | module.exports = Controller; -------------------------------------------------------------------------------- /6/api/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../util/baseFun'); 2 | 3 | class Controller { 4 | constructor(res, req) { 5 | this.res = res; 6 | this.req = req; 7 | } 8 | 9 | /** 10 | * 11 | * @description 设置响应数据 12 | * @param object res http res 13 | * @param boolean ret boolean 14 | * @param string message string 15 | * @param object dataInfo object 16 | * @param int httpStatus 17 | */ 18 | resApi(ret, message, dataInfo, httpStatus=200) { 19 | return baseFun.setResInfo(this.res, ret, message, dataInfo, httpStatus); 20 | } 21 | } 22 | 23 | module.exports = Controller; -------------------------------------------------------------------------------- /6/cpu/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../util/baseFun'); 2 | 3 | class Controller { 4 | constructor(res, req) { 5 | this.res = res; 6 | this.req = req; 7 | } 8 | 9 | /** 10 | * 11 | * @description 设置响应数据 12 | * @param object res http res 13 | * @param boolean ret boolean 14 | * @param string message string 15 | * @param object dataInfo object 16 | * @param int httpStatus 17 | */ 18 | resApi(ret, message, dataInfo, httpStatus=200) { 19 | return baseFun.setResInfo(this.res, ret, message, dataInfo, httpStatus); 20 | } 21 | } 22 | 23 | module.exports = Controller; -------------------------------------------------------------------------------- /13/src/controller/v1/sql.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const Controller = require('../../core/controller'); 4 | 5 | class Sql extends Controller { 6 | 7 | index() { 8 | const params = querystring.parse(this.ctx.request.querystring); 9 | 10 | let name = decodeURI(params['name']); 11 | 12 | /// connection 是 mysql 的链接句柄 13 | let queryStr = 'SELECT * FROM student WHERE name = "' + name + '"'; 14 | //connection.query(queryStr, function(err, results) {}); 15 | console.log(queryStr); 16 | 17 | return this.resApi(true, 'good', queryStr); 18 | } 19 | 20 | } 21 | 22 | module.exports = Sql; 23 | 24 | -------------------------------------------------------------------------------- /14/src/controller/v1/sql.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const Controller = require('../../core/controller'); 4 | 5 | class Sql extends Controller { 6 | 7 | index() { 8 | const params = querystring.parse(this.ctx.request.querystring); 9 | 10 | let name = decodeURI(params['name']); 11 | 12 | /// connection 是 mysql 的链接句柄 13 | let queryStr = 'SELECT * FROM student WHERE name = "' + name + '"'; 14 | //connection.query(queryStr, function(err, results) {}); 15 | console.log(queryStr); 16 | 17 | return this.resApi(true, 'good', queryStr); 18 | } 19 | 20 | } 21 | 22 | module.exports = Sql; 23 | 24 | -------------------------------------------------------------------------------- /12/cpu/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /12/cpu_opt/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /12/disk_io/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /12/example/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /7/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | const ContentModel = require('../model/content'); 3 | const contentService = require('../service/content')(); 4 | 5 | class Content extends Controller { 6 | 7 | constructor(res, req) { 8 | super(res, req); 9 | } 10 | 11 | async list() { 12 | let contentList = await new ContentModel().getList(); 13 | 14 | contentList = await contentService.filterUserinfo(contentList); 15 | 16 | return this.resApi(true, 'success', contentList); 17 | } 18 | 19 | test() { 20 | return this.resApi(true, 'good'); 21 | } 22 | } 23 | 24 | module.exports = Content; -------------------------------------------------------------------------------- /12/disk_io_opt/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /12/network_io/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /3/msvc/controller/content.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | const ContentModel = require('../model/content'); 3 | const contentService = require('../service/content')(); 4 | 5 | class Content extends Controller { 6 | 7 | constructor(res, req) { 8 | super(res, req); 9 | } 10 | 11 | async list() { 12 | let contentList = await new ContentModel().getList(); 13 | 14 | contentList = await contentService.filterUserinfo(contentList); 15 | 16 | return this.resApi(true, 'success', contentList); 17 | } 18 | 19 | test() { 20 | return this.resApi(true, 'good'); 21 | } 22 | } 23 | 24 | module.exports = Content; -------------------------------------------------------------------------------- /12/network_io_opt/lib/v8_profiler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const v8Profiler = require('v8-profiler-next'); 3 | const fs = require('fs'); 4 | // 设置采集数据保存的文件名 5 | const title = 'example'; 6 | 7 | module.exports = { 8 | 'start' : () => { 9 | // 启动采集,如果需要定时采集,可以将 title 设置为一个动态的根据时间变化的值 10 | v8Profiler.startProfiling(title, true); 11 | setTimeout(() => { // 30 秒后采集并导出 12 | const profile = v8Profiler.stopProfiling(title); 13 | profile.export(function (error, result) { // 将内容写入指定文件 14 | fs.writeFileSync(`./cpu_profiler/${title}.cpuprofile`, result); 15 | profile.delete(); 16 | }); 17 | }, 30 * 1000); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /11/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const app = new Koa(); 3 | const routerMiddleware = require('./src/middleware/router'); 4 | //const routerMiddleware = require('./src/middleware/newRouter'); 5 | const logCenter = require('./src/middleware/logCenter'); 6 | const session = require('./src/middleware/session'); 7 | 8 | const dumpFun = require('./src/lib/heapdump'); 9 | 10 | app.use(logCenter()); 11 | app.use(session()); 12 | app.use(routerMiddleware()); 13 | 14 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); 15 | 16 | /// 为了方便,可以打开如下代码自动获取 17 | const currentDate = new Date(); 18 | dumpFun('nodejs-cloumn', `${currentDate.getHours()}:${currentDate.getMinutes()+1}`, 60); -------------------------------------------------------------------------------- /12/network_io_opt/lib/call_api.js: -------------------------------------------------------------------------------- 1 | // 引入 request 库,需要在 package.json 中申明,并且 npm install 2 | const request = require('request'); 3 | // 缓存 api 请求结果数据 4 | const apiCacheData = {}; 5 | 6 | /** 7 | * 8 | * request 调用外部 api 9 | * @param {*} apiLink string 10 | * @param {*} callback funtion 11 | * 12 | */ 13 | module.exports = (apiLink, callback) => { 14 | if(apiCacheData[apiLink]) { 15 | return callback(apiCacheData[apiLink]); 16 | } 17 | request(apiLink, {timeout: 3000}, function (error, response, body) { 18 | if(error) { 19 | callback(false); 20 | } else { 21 | apiCacheData[apiLink] = body; 22 | callback(body); 23 | } 24 | }); 25 | } -------------------------------------------------------------------------------- /18/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | const checkToken = require('./src/middleware/checkToken'); 6 | const routerMiddleware = require('./src/middleware/router'); 7 | //const backendRouter = require('./src/middleware/backendRouter'); 8 | const logCenter = require('./src/middleware/logCenter'); 9 | const security = require('./src/middleware/security'); 10 | 11 | app.use(logCenter()); 12 | app.use(security()); 13 | app.use(checkToken()); 14 | app.use(koaBody({ 15 | multipart: true 16 | })); 17 | app.use(routerMiddleware()); 18 | //app.use(backendRouter()); 19 | 20 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /4/express/myapp/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.listen(port, () => console.log(`Example app listening on port ${port}!`)) 6 | /** 7 | * 中间件 1 8 | */ 9 | app.use((req, res, next) => { 10 | console.log('first'); 11 | next(); 12 | console.log('first end'); 13 | }); 14 | /** 15 | * 中间件 2 16 | */ 17 | app.use((req, res, next) => { 18 | console.log('second'); 19 | next(); 20 | console.log('second end'); 21 | }); 22 | /** 23 | * 中间件 3 24 | */ 25 | app.use((req, res, next) => { 26 | console.log('third'); 27 | next(); 28 | console.log('third end'); 29 | }); 30 | 31 | app.get('/', (req, res) => res.send('Hello World!')) 32 | 33 | -------------------------------------------------------------------------------- /16/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | 15 | /** 16 | * 17 | * @param {string} logType 日志类型 info | error | warning | debug 18 | * @param {object} logInfo 日志信息 19 | */ 20 | log(logType, logInfo) { 21 | return this.ctx.log.add(logType, this.ctx.pathname, logInfo); 22 | } 23 | } 24 | 25 | module.exports = Model; -------------------------------------------------------------------------------- /17/src/core/model.js: -------------------------------------------------------------------------------- 1 | const baseMongo = require('../core/baseMongodb')(); 2 | 3 | class Model { 4 | constructor() { 5 | this.db = 'nodejs_cloumn'; 6 | this.baseMongo = baseMongo; 7 | } 8 | 9 | async get(collectionName) { 10 | const client = await this.baseMongo.getClient(); 11 | const collection = client.db(this.db).collection(collectionName); 12 | return collection; 13 | } 14 | 15 | /** 16 | * 17 | * @param {string} logType 日志类型 info | error | warning | debug 18 | * @param {object} logInfo 日志信息 19 | */ 20 | log(logType, logInfo) { 21 | return this.ctx.log.add(logType, this.ctx.pathname, logInfo); 22 | } 23 | } 24 | 25 | module.exports = Model; -------------------------------------------------------------------------------- /12/network_io/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | // 引入 v8-profiler 库,可以作为一个中间件来实现 3 | const v8Profiler = require('./lib/v8_profiler'); 4 | // 引入 api 库 5 | const callApi = require('./lib/call_api'); 6 | 7 | /** 8 | * 9 | * 创建 http 服务,简单返回 10 | */ 11 | const server = http.createServer((req, res) => { 12 | callApi('http://127.0.0.1:4000', (ret) => { // 调用 4000 服务,并显示返回结果 13 | if(ret) { 14 | res.write(ret); 15 | } else { 16 | res.write('call api server error'); 17 | } 18 | res.end(); 19 | }); 20 | }); 21 | /** 22 | * 23 | * 启动服务,并开始执行 v8 profiler 的采集工作 24 | */ 25 | server.listen(3000, () => { 26 | console.log('server start http://127.0.0.1:3000'); 27 | v8Profiler.start(); 28 | }); -------------------------------------------------------------------------------- /12/network_io_opt/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | // 引入 v8-profiler 库,可以作为一个中间件来实现 3 | const v8Profiler = require('./lib/v8_profiler'); 4 | // 引入 api 库 5 | const callApi = require('./lib/call_api'); 6 | 7 | /** 8 | * 9 | * 创建 http 服务,简单返回 10 | */ 11 | const server = http.createServer((req, res) => { 12 | callApi('http://127.0.0.1:4000', (ret) => { // 调用 4000 服务,并显示返回结果 13 | if(ret) { 14 | res.write(ret); 15 | } else { 16 | res.write('call api server error'); 17 | } 18 | res.end(); 19 | }); 20 | }); 21 | /** 22 | * 23 | * 启动服务,并开始执行 v8 profiler 的采集工作 24 | */ 25 | server.listen(3000, () => { 26 | console.log('server start http://127.0.0.1:3000'); 27 | v8Profiler.start(); 28 | }); -------------------------------------------------------------------------------- /19/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "node app", 9 | "clinic-test": "cd bin;node clinic_test.js;cd .." 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "install": "^0.13.0", 15 | "koa": "^2.13.1", 16 | "koa-better-http-proxy": "^0.2.9", 17 | "koa-body": "^4.2.0", 18 | "lodash": "^4.17.21", 19 | "moment": "^2.29.1", 20 | "mongodb": "^3.6.6", 21 | "node-cache": "^5.1.2", 22 | "npm": "^7.7.6", 23 | "redis": "^3.0.2", 24 | "request": "^2.88.2", 25 | "request-promise": "^4.2.6", 26 | "util": "^0.12.3" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /12/cpu/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /12/api_server/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /12/cpu_opt/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /12/disk_io/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /12/example/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /12/disk_io_opt/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "nan": { 8 | "version": "2.14.2", 9 | "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz", 10 | "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==" 11 | }, 12 | "v8-profiler-next": { 13 | "version": "1.3.0", 14 | "resolved": "https://registry.npmjs.org/v8-profiler-next/-/v8-profiler-next-1.3.0.tgz", 15 | "integrity": "sha512-UrG750R9s43a3vInsLFHBnL8EbkSJ8d/yovYRKLk1myDeW2xdcQgcEKzVzlxLNDgULgDoLALn02VSw8BTH8M3w==", 16 | "requires": { 17 | "nan": "^2.14.1" 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /1/practice/sync.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | /** 3 | * 4 | * 创建 http 服务,简单返回 5 | */ 6 | const server = http.createServer((req, res) => { 7 | res.write(`${startCount() + nextCount()}`); 8 | res.end(); 9 | }); 10 | 11 | /** 12 | * 从 0 计算到 500000000 的和 13 | */ 14 | function startCount() { 15 | let sum = 0; 16 | for(let i=0; i<500000000; i++){ 17 | sum = sum + i; 18 | } 19 | return sum; 20 | } 21 | 22 | /** 23 | * 从 500000000 计算到 1000000000 之间的和 24 | */ 25 | function nextCount() { 26 | let sum = 0; 27 | for(let i=500000000; i<1000000000; i++){ 28 | sum = sum + i; 29 | } 30 | return sum; 31 | } 32 | /** 33 | * 34 | * 启动服务 35 | */ 36 | server.listen(4000, () => { 37 | console.log('server start http://127.0.0.1:4000'); 38 | }); -------------------------------------------------------------------------------- /18/src/middleware/checkToken.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const baseFun = require('../lib/baseFun'); 4 | 5 | const tokenMapping = { 6 | 'piu12naern9023izcx' : '1001', 7 | 'dopu89y762yimb239x' : '1002' 8 | }; 9 | 10 | module.exports = function () { 11 | return async function ( ctx, next ) { 12 | const params = querystring.parse(ctx.request.querystring); 13 | let token = ctx.request.headers.token || params['token']; 14 | if(!token && !tokenMapping[token]){ 15 | return baseFun.setResInfo(ctx, false, 'pls login first', null, 401); 16 | } 17 | ctx.userId = tokenMapping[token]; 18 | //ctx.userId = `${ Math.floor(Math.random() * (10000000 - 1000) + 1000)}`; 19 | await next(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /19/src/middleware/checkToken.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | 3 | const baseFun = require('../lib/baseFun'); 4 | 5 | const tokenMapping = { 6 | 'piu12naern9023izcx' : '1001', 7 | 'dopu89y762yimb239x' : '1002' 8 | }; 9 | 10 | module.exports = function () { 11 | return async function ( ctx, next ) { 12 | const params = querystring.parse(ctx.request.querystring); 13 | let token = ctx.request.headers.token || params['token']; 14 | if(!token && !tokenMapping[token]){ 15 | return baseFun.setResInfo(ctx, false, 'pls login first', null, 401); 16 | } 17 | ctx.userId = tokenMapping[token]; 18 | //ctx.userId = `${ Math.floor(Math.random() * (10000000 - 1000) + 1000)}`; 19 | await next(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /14/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "clinic-test": "cd bin;node clinic_test.js;cd .." 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cheerio": "^1.0.0-rc.5", 14 | "crawler": "^1.3.0", 15 | "heapdump": "^0.3.15", 16 | "install": "^0.13.0", 17 | "koa": "^2.13.1", 18 | "koa-body": "^4.2.0", 19 | "lodash": "^4.17.21", 20 | "node-cache": "^5.1.2", 21 | "node-html-parser": "^3.1.2", 22 | "npm": "^7.7.6", 23 | "puppeteer": "^8.0.0", 24 | "redis": "^3.0.2", 25 | "request": "^2.88.2", 26 | "request-promise": "^4.2.6", 27 | "util": "^0.12.3" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /15/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "clinic-test": "cd bin;node clinic_test.js;cd .." 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cheerio": "^1.0.0-rc.5", 14 | "crawler": "^1.3.0", 15 | "heapdump": "^0.3.15", 16 | "install": "^0.13.0", 17 | "koa": "^2.13.1", 18 | "koa-body": "^4.2.0", 19 | "lodash": "^4.17.21", 20 | "node-cache": "^5.1.2", 21 | "node-html-parser": "^3.1.2", 22 | "npm": "^7.7.6", 23 | "puppeteer": "^8.0.0", 24 | "redis": "^3.0.2", 25 | "request": "^2.88.2", 26 | "request-promise": "^4.2.6", 27 | "util": "^0.12.3" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /19/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const koaBody = require('koa-body'); 3 | 4 | const app = new Koa(); 5 | //const checkToken = require('./src/middleware/checkToken'); 6 | const routerMiddleware = require('./src/middleware/router'); 7 | //const backendRouter = require('./src/middleware/backendRouter'); 8 | const logCenter = require('./src/middleware/logCenter'); 9 | const security = require('./src/middleware/security'); 10 | 11 | app.use(logCenter()); 12 | app.use(security()); 13 | //app.use(checkToken()); 14 | app.use(koaBody({ 15 | multipart: true 16 | })); 17 | app.use(routerMiddleware()); 18 | //app.use(backendRouter()); 19 | 20 | if(process.env.SERVERLESS) { 21 | module.exports = app 22 | } else { 23 | app.listen(3000) 24 | } 25 | //app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /12/cpu/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | // 引入 v8-profiler 库,可以作为一个中间件来实现 3 | const v8Profiler = require('./lib/v8_profiler'); 4 | // 引入 md5 库 5 | const getMd5 = require('./lib/md5'); 6 | /** 7 | * 8 | * 创建 http 服务,简单返回 9 | */ 10 | const server = http.createServer((req, res) => { 11 | // 设置返回的字符串 12 | let ret; 13 | // 加密一组数据 14 | const md5List = ['hello', 'Node.js', 'lagou', 'is', 'great']; 15 | md5List.forEach( (str)=> { 16 | if(ret){ 17 | ret = `${ret} ${getMd5(str)}`; 18 | } else { 19 | ret = getMd5(str) 20 | } 21 | }); 22 | res.write(ret); 23 | res.end(); 24 | }); 25 | /** 26 | * 27 | * 启动服务,并开始执行 v8 profiler 的采集工作 28 | */ 29 | server.listen(3000, () => { 30 | console.log('server start http://127.0.0.1:3000'); 31 | v8Profiler.start(); 32 | }); -------------------------------------------------------------------------------- /12/cpu_opt/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | // 引入 v8-profiler 库,可以作为一个中间件来实现 3 | const v8Profiler = require('./lib/v8_profiler'); 4 | // 引入 md5 库 5 | const getMd5 = require('./lib/md5'); 6 | /** 7 | * 8 | * 创建 http 服务,简单返回 9 | */ 10 | const server = http.createServer((req, res) => { 11 | // 设置返回的字符串 12 | let ret; 13 | // 加密一组数据 14 | const md5List = ['hello', 'Node.js', 'lagou', 'is', 'great']; 15 | md5List.forEach( (str)=> { 16 | if(ret){ 17 | ret = `${ret} ${getMd5(str)}`; 18 | } else { 19 | ret = getMd5(str) 20 | } 21 | }); 22 | res.write(ret); 23 | res.end(); 24 | }); 25 | /** 26 | * 27 | * 启动服务,并开始执行 v8 profiler 的采集工作 28 | */ 29 | server.listen(3000, () => { 30 | console.log('server start http://127.0.0.1:3000'); 31 | v8Profiler.start(); 32 | }); -------------------------------------------------------------------------------- /16/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "clinic-test": "cd bin;node clinic_test.js;cd .." 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "puppeteer": "^8.0.0", 14 | "node-html-parser": "^3.1.2" 15 | }, 16 | "dependencies": { 17 | "heapdump": "^0.3.15", 18 | "install": "^0.13.0", 19 | "koa": "^2.13.1", 20 | "koa-better-http-proxy": "^0.2.9", 21 | "koa-body": "^4.2.0", 22 | "lodash": "^4.17.21", 23 | "moment": "^2.29.1", 24 | "node-cache": "^5.1.2", 25 | "npm": "^7.7.6", 26 | "redis": "^3.0.2", 27 | "request": "^2.88.2", 28 | "request-promise": "^4.2.6", 29 | "util": "^0.12.3" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /5/pm2/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 2, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /16/src/lib/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /17/src/lib/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /18/src/lib/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /19/src/lib/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /3/mvc/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /6/api/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /6/cpu/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /6/io/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /7/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /11/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /13/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /14/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /15/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /16/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /17/src/controller/act.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Act extends Controller { 4 | 5 | list() { 6 | return this.resApi(true, 'success', [ 7 | { 8 | "id":"111", 9 | "name":"抢洗头券", 10 | "desc":"周六日前往,可免费体验", 11 | "image":"xxxx", 12 | "start_time":1422222333, 13 | "end_time":1444444444 14 | } 15 | ]); 16 | } 17 | 18 | detail() { 19 | return this.resApi(true, 'success', 20 | { 21 | "id":"111", 22 | "name":"抢洗头券", 23 | "desc":"周六日前往,可免费体验", 24 | "image":"xxxx", 25 | "start_time":1422222333, 26 | "end_time":1444444444 27 | }); 28 | } 29 | 30 | } 31 | 32 | module.exports = Act; -------------------------------------------------------------------------------- /17/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /18/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /19/src/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /3/msvc/core/apiCenter.js: -------------------------------------------------------------------------------- 1 | const url = require('url'); 2 | const querystring = require('querystring'); 3 | const rq = require('request-promise'); 4 | 5 | /** 6 | * 7 | * @description 调用外部 api,暂时只处理 get 逻辑 8 | * @param string api 9 | * @param string method 10 | * @param object params 11 | */ 12 | async function callApi(api, params={}, method='get') { 13 | const paramsStr = querystring.stringify(params); 14 | if(api.indexOf('?') == -1) { 15 | api = `${api}?`; 16 | } 17 | api = `${api}${paramsStr}`; 18 | let retStr = await rq(api); 19 | try { 20 | retInfo = JSON.parse(retStr); 21 | } catch (error) { 22 | return false; 23 | } 24 | if(retInfo['ret'] != 0 || !retInfo['data']) { 25 | return false; 26 | } 27 | return retInfo['data']; 28 | } 29 | 30 | module.exports = { 31 | callApi 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /13/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /14/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /15/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /16/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /17/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /7/util/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(res, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | res.writeHead(httpStatus, { 'Content-Type': 'text/plain' }); 26 | res.write(JSON.stringify(retInfo)); 27 | res.end(); 28 | return; 29 | } 30 | 31 | module.exports = { 32 | setResInfo 33 | } -------------------------------------------------------------------------------- /10/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /11/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /13/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /14/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /16/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | 21 | /** 22 | * 23 | * @param {string} logType 日志类型 info | error | warning | debug 24 | * @param {object} logInfo 日志信息 25 | */ 26 | log(logType, logInfo) { 27 | return this.ctx.log.add(logType, this.ctx.pathname, logInfo); 28 | } 29 | } 30 | 31 | module.exports = Controller; -------------------------------------------------------------------------------- /17/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const baseFun = require('../lib/baseFun'); 2 | 3 | class Controller { 4 | constructor(ctx) { 5 | this.ctx = ctx; 6 | } 7 | 8 | /** 9 | * 10 | * @description 设置响应数据 11 | * @param object res http res 12 | * @param boolean ret boolean 13 | * @param string message string 14 | * @param object dataInfo object 15 | * @param int httpStatus 16 | */ 17 | resApi(ret, message, dataInfo, httpStatus=200) { 18 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 19 | } 20 | 21 | /** 22 | * 23 | * @param {string} logType 日志类型 info | error | warning | debug 24 | * @param {object} logInfo 日志信息 25 | */ 26 | log(logType, logInfo) { 27 | return this.ctx.log.add(logType, this.ctx.pathname, logInfo); 28 | } 29 | } 30 | 31 | module.exports = Controller; -------------------------------------------------------------------------------- /3/mvc/util/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(res, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | res.writeHead(httpStatus, { 'Content-Type': 'text/plain' }); 26 | res.write(JSON.stringify(retInfo)); 27 | res.end(); 28 | return; 29 | } 30 | 31 | module.exports = { 32 | setResInfo 33 | } -------------------------------------------------------------------------------- /6/api/util/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(res, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | res.writeHead(httpStatus, { 'Content-Type': 'text/plain' }); 26 | res.write(JSON.stringify(retInfo)); 27 | res.end(); 28 | return; 29 | } 30 | 31 | module.exports = { 32 | setResInfo 33 | } -------------------------------------------------------------------------------- /6/cpu/util/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(res, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | res.writeHead(httpStatus, { 'Content-Type': 'text/plain' }); 26 | res.write(JSON.stringify(retInfo)); 27 | res.end(); 28 | return; 29 | } 30 | 31 | module.exports = { 32 | setResInfo 33 | } -------------------------------------------------------------------------------- /6/io/util/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(res, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | res.writeHead(httpStatus, { 'Content-Type': 'text/plain' }); 26 | res.write(JSON.stringify(retInfo)); 27 | res.end(); 28 | return; 29 | } 30 | 31 | module.exports = { 32 | setResInfo 33 | } -------------------------------------------------------------------------------- /8/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: false, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /9/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /6/api/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-api", // 启动进程名 4 | script: "./index.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: false, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-cp/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-cp/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /6/cpu/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-cpu", // 启动进程名 4 | script: "./index.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: false, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-cp/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-cp/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /6/io/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-column-io", // 启动进程名 4 | script: "./index.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: false, // 开发环境使用 true,其他必须设置为 false 10 | }, 11 | env_testing: { 12 | NODE_ENV: "testing", 13 | watch: false, // 开发环境使用 true,其他必须设置为 false 14 | }, 15 | env_production: { 16 | NODE_ENV: "production", 17 | watch: false, // 开发环境使用 true,其他必须设置为 false 18 | }, 19 | log_date_format: 'YYYY-MM-DD HH:mm Z', 20 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 21 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 22 | max_restarts: 10, 23 | 24 | }] 25 | } -------------------------------------------------------------------------------- /10/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = JSON.stringify(retInfo); 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /11/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = JSON.stringify(retInfo); 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /8/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = JSON.stringify(retInfo); 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /9/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = JSON.stringify(retInfo); 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /18/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : dataInfo ? dataInfo : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /19/src/lib/baseFun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @description 设置响应数据 4 | * @param object res http res 5 | * @param boolean ret boolean 6 | * @param string message string 7 | * @param object dataInfo object 8 | * @param int httpStatus 9 | */ 10 | function setResInfo(ctx, ret, message, dataInfo, httpStatus=200) { 11 | let retInfo = {}; 12 | if(!ret) { 13 | retInfo = { 14 | 'ret' : -1, 15 | 'message' : message ? message : 'error', 16 | 'data' : dataInfo ? dataInfo : {} 17 | }; 18 | } else { 19 | retInfo = { 20 | 'ret' : 0, 21 | 'message' : message ? message : 'success', 22 | 'data' : dataInfo ? dataInfo : {} 23 | }; 24 | } 25 | 26 | ctx.response.type = 'text/plain'; 27 | ctx.response.status = httpStatus; 28 | ctx.response.body = retInfo; 29 | return; 30 | } 31 | 32 | module.exports = { 33 | setResInfo 34 | } -------------------------------------------------------------------------------- /17/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "clinic-test": "cd bin;node clinic_test.js;cd .." 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cheerio": "^1.0.0-rc.5", 14 | "crawler": "^1.3.0", 15 | "heapdump": "^0.3.15", 16 | "http-proxy": "^1.18.1", 17 | "install": "^0.13.0", 18 | "koa": "^2.13.1", 19 | "koa-better-http-proxy": "^0.2.9", 20 | "koa-body": "^4.2.0", 21 | "lodash": "^4.17.21", 22 | "moment": "^2.29.1", 23 | "node-cache": "^5.1.2", 24 | "node-html-parser": "^3.1.2", 25 | "npm": "^7.7.6", 26 | "puppeteer": "^8.0.0", 27 | "redis": "^3.0.2", 28 | "request": "^2.88.2", 29 | "request-promise": "^4.2.6", 30 | "util": "^0.12.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /1/practice/async.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const rp = require('request-promise'); 3 | /** 4 | * 5 | * 创建 http 服务,简单返回 6 | */ 7 | const server = http.createServer((req, res) => { 8 | Promise.all([startCount(), nextCount()]).then((values) => { 9 | let sum = values.reduce(function(prev, curr, idx, arr){ 10 | return parseInt(prev) + parseInt(curr); 11 | }) 12 | res.write(`${sum}`); 13 | res.end(); 14 | }) 15 | }); 16 | 17 | /** 18 | * 从 0 计算到 500000000 的和 19 | */ 20 | async function startCount() { 21 | return await rp.get('http://127.0.0.1:5000'); 22 | } 23 | 24 | /** 25 | * 从 500000000 计算到 1000000000 之间的和 26 | */ 27 | async function nextCount() { 28 | return await rp.get('http://127.0.0.1:6000'); 29 | } 30 | 31 | /** 32 | * 33 | * 启动服务 34 | */ 35 | server.listen(4000, () => { 36 | console.log('server start http://127.0.0.1:4000'); 37 | }); -------------------------------------------------------------------------------- /12/disk_io_opt/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const fs = require('fs'); 3 | // 引入 v8-profiler 库,可以作为一个中间件来实现 4 | const v8Profiler = require('./lib/v8_profiler'); 5 | // 文件缓存 6 | let fileCache; 7 | 8 | /** 9 | * 10 | * 创建 http 服务,简单返回 11 | */ 12 | const server = http.createServer((req, res) => { 13 | if(fileCache) { 14 | res.write(fileCache); 15 | res.end(); 16 | return; 17 | } 18 | fs.readFile('./test_file.conf', (err, data) => { 19 | if (err) { 20 | res.write('error read file'); 21 | res.end(); 22 | } else { 23 | fileCache = data; 24 | res.write(data); 25 | res.end(); 26 | } 27 | }); 28 | }); 29 | /** 30 | * 31 | * 启动服务,并开始执行 v8 profiler 的采集工作 32 | */ 33 | server.listen(3000, () => { 34 | console.log('server start http://127.0.0.1:3000'); 35 | v8Profiler.start(); 36 | }); -------------------------------------------------------------------------------- /10/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /11/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /13/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /14/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /8/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /9/src/controller/localCache.js: -------------------------------------------------------------------------------- 1 | const NodeCache = require( "node-cache"); 2 | const cacheHandle = new NodeCache(); 3 | 4 | const Controller = require('../core/controller'); 5 | 6 | class LocalCache extends Controller { 7 | 8 | yes() { 9 | let result = cacheHandle.get('result'); 10 | if(!result || result == 0){ // result 为函数本地内存缓存 11 | result = 0; 12 | for(let i=0; i<1000000000; i++){ 13 | result = result + i; 14 | } 15 | cacheHandle.set('result', result) 16 | } 17 | return this.resApi(true, 'success', `cache sum 0 - 1000000000 is ${result}`); 18 | } 19 | 20 | no() { 21 | let sum = 0; 22 | for(let i=0; i<1000000000; i++){ 23 | sum = sum + i; 24 | } 25 | return this.resApi(true, 'success', `no cache sum 0 - 1000000000 is ${sum}`); 26 | } 27 | } 28 | 29 | module.exports = LocalCache; -------------------------------------------------------------------------------- /18/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "8", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "clinic-test": "cd bin;node clinic_test.js;cd .." 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cheerio": "^1.0.0-rc.5", 14 | "crawler": "^1.3.0", 15 | "heapdump": "^0.3.15", 16 | "http-proxy": "^1.18.1", 17 | "install": "^0.13.0", 18 | "koa": "^2.13.1", 19 | "koa-better-http-proxy": "^0.2.9", 20 | "koa-body": "^4.2.0", 21 | "lodash": "^4.17.21", 22 | "moment": "^2.29.1", 23 | "mongodb": "^3.6.6", 24 | "node-cache": "^5.1.2", 25 | "node-html-parser": "^3.1.2", 26 | "npm": "^7.7.6", 27 | "puppeteer": "^8.0.0", 28 | "redis": "^3.0.2", 29 | "request": "^2.88.2", 30 | "request-promise": "^4.2.6", 31 | "util": "^0.12.3" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /3/msvc/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /3/mvc/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /6/api/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /6/cpu/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /6/io/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /18/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-main-server-3000", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | ignore_watch: ["log", "node_modules", "bin", "config"], 11 | }, 12 | env_testing: { 13 | NODE_ENV: "testing", 14 | watch: false, // 开发环境使用 true,其他必须设置为 false 15 | }, 16 | env_production: { 17 | NODE_ENV: "production", 18 | watch: false, // 开发环境使用 true,其他必须设置为 false 19 | }, 20 | log_date_format: 'YYYY-MM-DD HH:mm Z', 21 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 22 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 23 | max_restarts: 10, 24 | 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /19/pm2.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: "nodejs-main-server-3000", // 启动进程名 4 | script: "./app.js", // 启动文件 5 | instances: 1, // 启动进程数 6 | exec_mode: 'cluster', // 多进程多实例 7 | env_development: { 8 | NODE_ENV: "development", 9 | watch: true, // 开发环境使用 true,其他必须设置为 false 10 | ignore_watch: ["log", "node_modules", "bin", "config"], 11 | }, 12 | env_testing: { 13 | NODE_ENV: "testing", 14 | watch: false, // 开发环境使用 true,其他必须设置为 false 15 | }, 16 | env_production: { 17 | NODE_ENV: "production", 18 | watch: false, // 开发环境使用 true,其他必须设置为 false 19 | }, 20 | log_date_format: 'YYYY-MM-DD HH:mm Z', 21 | error_file: '~/data/nodejs-column-io/err.log', // 错误日志文件,必须设置在项目外的目录,这里为了测试 22 | out_file: '~/data/nodejs-column-io/info.log', // 流水日志,包括 console.log 日志,必须设置在项目外的目录,这里为了测试 23 | max_restarts: 10, 24 | 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /7/core/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /18/src/lib/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true}); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /19/src/lib/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true}); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /3/api-server/lib/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true}); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /3/restful/lib/baseMongodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description 封装 mongodb api 3 | */ 4 | const uri = "mongodb+srv://test:test@cluster0.ejxpm.mongodb.net/"; 5 | const MongoClient = require('mongodb').MongoClient; 6 | 7 | let baseMongodb; 8 | 9 | class BaseMongodb { 10 | constructor() { 11 | this.mongoClient = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true}); 12 | this.mongoClient.connect(err => { 13 | if(err){ 14 | console.log('connect db error', err); 15 | return; 16 | } 17 | this.client = this.mongoClient; 18 | }); 19 | } 20 | 21 | async getClient() { 22 | if(!this.client) { 23 | this.client = await this.mongoClient.connect(); 24 | } 25 | return this.client; 26 | } 27 | } 28 | 29 | module.exports = () => { 30 | if(!baseMongodb){ 31 | baseMongodb = new BaseMongodb(); 32 | } 33 | return baseMongodb; 34 | } -------------------------------------------------------------------------------- /6/io/controller/test.js: -------------------------------------------------------------------------------- 1 | const rp = require('request-promise'); 2 | 3 | const Controller = require('../core/controller'); 4 | 5 | class Test extends Controller { 6 | 7 | constructor(res, req) { 8 | super(res, req); 9 | } 10 | /** 11 | * 复杂运算 12 | */ 13 | async bad() { 14 | let result = await rp.get('http://127.0.0.1:3000/v1/cpu'); 15 | 16 | let sumData = JSON.parse(result); 17 | let sum = sumData && sumData.data ? sumData.data.sum : false; 18 | return this.resApi(true, 'success', {'sum' : sum}); 19 | } 20 | 21 | /** 22 | * 正常请求 23 | */ 24 | normal() { 25 | return this.resApi(true, 'good', 'hello world io'); 26 | } 27 | 28 | /** 29 | * 正常请求,api call 网络 I/O 30 | */ 31 | async normalCall() { 32 | let result = await rp.get('http://127.0.0.1:5000/v1/normal'); 33 | 34 | let dataInfo = JSON.parse(result); 35 | let info = dataInfo && dataInfo.data ? dataInfo.data : false; 36 | return this.resApi(true, 'success', info); 37 | } 38 | } 39 | 40 | module.exports = Test; -------------------------------------------------------------------------------- /4/koa/myapp-async/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa'); 2 | const app = new Koa(); 3 | /** 4 | * 中间件 1 5 | */ 6 | app.use(async (ctx, next) => { 7 | console.log('first'); 8 | await next(); 9 | console.log('first end'); 10 | }); 11 | 12 | /** 13 | * 中间件 2 14 | */ 15 | app.use(async (ctx, next) => { 16 | console.log('second'); 17 | await next(); 18 | console.log('second end'); 19 | }); 20 | 21 | /** 22 | * 异步中间件 23 | */ 24 | app.use(async (ctx, next) => { 25 | console.log('async'); 26 | await next(); 27 | await new Promise( 28 | (resolve) => 29 | setTimeout( 30 | () => { 31 | console.log(`wait 1000 ms end`); 32 | resolve() 33 | }, 34 | 1000 35 | ) 36 | ); 37 | console.log('async end'); 38 | }); 39 | 40 | /** 41 | * 中间件 3 42 | */ 43 | app.use(async (ctx, next) => { 44 | console.log('third'); 45 | await next(); 46 | console.log('third end'); 47 | }); 48 | app.use(async ctx => { 49 | ctx.body = 'Hello World'; 50 | }); 51 | 52 | app.listen(3000, () => console.log(`Example app listening on port 3000!`)); -------------------------------------------------------------------------------- /4/express/myapp-async/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.listen(port, () => console.log(`Example app listening on port ${port}!`)) 6 | /** 7 | * 中间件 1 8 | */ 9 | app.use(async (req, res, next) => { 10 | console.log('first'); 11 | await next(); 12 | console.log('first end'); 13 | }); 14 | /** 15 | * 中间件 2 16 | */ 17 | app.use(async (req, res, next) => { 18 | console.log('second'); 19 | await next(); 20 | console.log('second end'); 21 | }); 22 | 23 | /** 24 | * 异步中间件 25 | */ 26 | app.use(async (req, res, next) => { 27 | console.log('async'); 28 | await next(); 29 | await new Promise( 30 | (resolve) => 31 | setTimeout( 32 | () => { 33 | console.log(`wait ${s} ms end`); 34 | resolve() 35 | }, 36 | 1000) 37 | ); 38 | console.log('async end'); 39 | }); 40 | 41 | /** 42 | * 中间件 3 43 | */ 44 | app.use(async (req, res, next) => { 45 | console.log('third'); 46 | await next(); 47 | console.log('third end'); 48 | }); 49 | 50 | app.get('/', (req, res) => res.send('Hello World!')) 51 | 52 | -------------------------------------------------------------------------------- /18/src/service/history.js: -------------------------------------------------------------------------------- 1 | const moment = require('moment'); 2 | 3 | const Service = require('../core/service'); 4 | const load = require('../core/load'); 5 | 6 | class HistoryService extends Service { 7 | async insertHistory(actId, ticketCode) { 8 | const codeModel = load.loadModel(this.ctx, 'code'); 9 | 10 | const codeInfo = await codeModel.getInfoByCode(ticketCode); 11 | if(!codeInfo) { // 该类告警比较严重,如果出现该问题,则应迅速排查,不过这时候票已经属于该用户,问题倒不是非常严重 12 | this.log('error', 'can not find code info, import code error', {actId, ticketCode}) 13 | } 14 | const historyModel = load.loadModel(this.ctx, 'history'); 15 | 16 | const rowInfo = { 17 | 'user_id' : this.ctx.userId, 18 | 'code_id' : codeInfo['_id'], 19 | 'time' : moment().unix(), 20 | 'is_effective' : true 21 | }; 22 | 23 | const ret = await historyModel.insertOne(rowInfo); 24 | if(!ret){ // 此类告警同样重要,不过这时候票已经属于该用户,问题倒不是非常严重 25 | this.log('error', 'insert history error, user will not see his ticket code', {rowInfo}); 26 | return false; 27 | } 28 | return true; 29 | } 30 | } 31 | 32 | module.exports = HistoryService; -------------------------------------------------------------------------------- /18/src/model/act.js: -------------------------------------------------------------------------------- 1 | const moment = require('moment'); 2 | const Model = require('../core/model'); 3 | 4 | class ActModel extends Model { 5 | constructor(ctx) { 6 | super(ctx); 7 | this.collectionName = 'act'; 8 | } 9 | 10 | async getOnlinList(page=0, pageSize=20) { 11 | const currentTimestamp = moment().unix(); 12 | const queryOption = { 13 | 'start_time' : { 14 | '$lt' : currentTimestamp, 15 | }, 16 | 'end_time' : { 17 | '$gt' : currentTimestamp, 18 | } 19 | }; 20 | 21 | return await this.getList(queryOption, {'start_time':-1}, pageSize, page*pageSize); 22 | } 23 | 24 | async getOneByAid(aid) { 25 | if(!aid){ 26 | return false; 27 | } 28 | const collection = await this.get(); 29 | const queryOption = { 30 | 'aid' : aid 31 | }; 32 | const queryArr = await collection.find(queryOption).toArray(); 33 | if(!queryArr || queryArr.length < 1){ 34 | return false; 35 | } 36 | const rowInfo = queryArr.pop(); 37 | rowInfo['_id'] = rowInfo['_id'].toString(); 38 | 39 | return rowInfo; 40 | } 41 | } 42 | 43 | module.exports = ActModel; -------------------------------------------------------------------------------- /18/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | const baseFun = require('../lib/baseFun'); 3 | 4 | class Controller { 5 | constructor(ctx) { 6 | this.ctx = ctx; 7 | } 8 | 9 | /** 10 | * 11 | * @param {string} key 12 | * @param {any} def 13 | */ 14 | getParams(key, def='') { 15 | const params = querystring.parse(this.ctx.request.querystring); 16 | let value = params[key]; 17 | if(!value) { 18 | return def; 19 | } 20 | return decodeURI(value).trim(); 21 | } 22 | 23 | /** 24 | * 25 | * @description 设置响应数据 26 | * @param object res http res 27 | * @param boolean ret boolean 28 | * @param string message string 29 | * @param object dataInfo object 30 | * @param int httpStatus 31 | */ 32 | resApi(ret, message, dataInfo, httpStatus=200) { 33 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 34 | } 35 | 36 | /** 37 | * 38 | * @param {string} logType 日志类型 info | error | warning | debug 39 | * @param {string} message 消息 40 | * @param {object} logInfo 日志信息 41 | */ 42 | log(logType, message, logInfo) { 43 | return this.ctx.log.add(logType, this.ctx.pathname, message, logInfo); 44 | } 45 | } 46 | 47 | module.exports = Controller; -------------------------------------------------------------------------------- /17/src/controller/ticket.js: -------------------------------------------------------------------------------- 1 | const Controller = require('../core/controller'); 2 | 3 | class Ticket extends Controller { 4 | 5 | get() { 6 | return this.resApi(true, 'success', { 7 | "id":"111", 8 | "name":"洗头券", 9 | "desc":"周六日前往,可免费体验", 10 | "actId":"1110", 11 | "isEffective": true, 12 | "image":"xxxx", 13 | "start_time":1422222333, 14 | "end_time":1444444444 15 | }); 16 | } 17 | 18 | detail() { 19 | return this.resApi(true, 'success',{ 20 | "id":"111", 21 | "name":"洗头券", 22 | "code":"xxxx11", 23 | "desc":"周六日前往,可免费体验", 24 | "actId":"1110", 25 | "isEffective": true, 26 | "image":"xxxx", 27 | "start_time":1422222333, 28 | "end_time":1444444444 29 | }); 30 | } 31 | 32 | list() { 33 | return this.resApi(true, 'success',[ 34 | { 35 | "id":"111", 36 | "name":"洗头券", 37 | "desc":"周六日前往,可免费体验", 38 | "code":"xxxx11", 39 | "actId":"1110", 40 | "isEffective": true, 41 | "start_time":1422222333, 42 | "end_time":1444444444 43 | } 44 | ]); 45 | } 46 | } 47 | 48 | module.exports = Ticket; -------------------------------------------------------------------------------- /19/src/core/controller.js: -------------------------------------------------------------------------------- 1 | const querystring = require('querystring'); 2 | const baseFun = require('../lib/baseFun'); 3 | 4 | class Controller { 5 | constructor(ctx) { 6 | this.ctx = ctx; 7 | } 8 | 9 | /** 10 | * 11 | * @param {string} key 12 | * @param {any} def 13 | */ 14 | getParams(key, def='') { 15 | const params = querystring.parse(this.ctx.request.querystring); 16 | let value = params[key]; 17 | if(!value) { 18 | return def; 19 | } 20 | return decodeURI(value).trim(); 21 | } 22 | 23 | /** 24 | * 25 | * @description 设置响应数据 26 | * @param object res http res 27 | * @param boolean ret boolean 28 | * @param string message string 29 | * @param object dataInfo object 30 | * @param int httpStatus 31 | */ 32 | resApi(ret, message, dataInfo, httpStatus=200) { 33 | httpStatus = parseInt(httpStatus); 34 | if(!httpStatus || httpStatus == 0){ 35 | httpStatus = 200; 36 | } 37 | return baseFun.setResInfo(this.ctx, ret, message, dataInfo, httpStatus); 38 | } 39 | 40 | /** 41 | * 42 | * @param {string} logType 日志类型 info | error | warning | debug 43 | * @param {string} message 消息 44 | * @param {object} logInfo 日志信息 45 | */ 46 | log(logType, message, logInfo) { 47 | return this.ctx.log.add(logType, this.ctx.pathname, message, logInfo); 48 | } 49 | } 50 | 51 | module.exports = Controller; -------------------------------------------------------------------------------- /16/src/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /17/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /17/src/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /18/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /18/src/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /19/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /19/src/config/lagou-nodejs.conf: -------------------------------------------------------------------------------- 1 | upstream lagou-nodejs { 2 | server 127.0.0.1:3000; 3 | server 127.0.0.1:3001; 4 | } 5 | upstream lagou-backend { 6 | server 127.0.0.1:3002; 7 | server 127.0.0.1:3003; 8 | } 9 | server { 10 | listen 80; 11 | server_name lagou-nodejs.com; 12 | 13 | # Load configuration files for the default server block. 14 | 15 | location /test/index { 16 | proxy_redirect off; 17 | proxy_set_header Host $host; 18 | proxy_set_header X-Real-IP $remote_addr; 19 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 20 | proxy_pass http://lagou-nodejs; 21 | 22 | } 23 | 24 | location ^~ /music/ { 25 | proxy_redirect off; 26 | proxy_set_header Host $host; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 29 | proxy_pass http://lagou-nodejs; 30 | 31 | } 32 | 33 | location / { 34 | proxy_redirect off; 35 | proxy_set_header Host $host; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | proxy_pass http://lagou-backend; 39 | } 40 | 41 | error_page 404 /404.html; 42 | location = /40x.html { 43 | } 44 | 45 | error_page 500 502 503 504 /50x.html; 46 | location = /50x.html { 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /6/api/service/content.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../core/apiCenter'); 2 | 3 | let contentService; 4 | 5 | class ContentService { 6 | async filterUserinfo(contents) { 7 | let userIds = []; 8 | contents.forEach(content => { 9 | if(content['user_id']){ 10 | userIds.push(content['user_id']); 11 | } 12 | }); 13 | if(userIds.length < 1){ 14 | return this._addUserinfo(contents); 15 | } 16 | 17 | let userinfos = await ApiCenter.callApi('http://127.0.0.1:5000/v1/userinfos', {user_ids: userIds.join(',')}); 18 | if(!userinfos || userinfos.length < 1) { 19 | return this._addUserinfo(contents); 20 | } 21 | 22 | let mapUserinfo = {}; 23 | userinfos.forEach(item => { 24 | if(userIds.includes(item.id)){ 25 | mapUserinfo[item.id] = item; 26 | } 27 | }); 28 | 29 | return this._addUserinfo(contents, mapUserinfo); 30 | } 31 | 32 | /** 33 | * 34 | * @desc 在 content 中增加 userinfo 35 | * @param {*} contents 36 | * @param {*} userinfo 37 | */ 38 | _addUserinfo(contents, mapUserinfo={}) { 39 | contents = contents.map(content => { 40 | content['user_info'] = mapUserinfo[content['user_id']] ? mapUserinfo[content['user_id']] : {}; 41 | return content; 42 | }); 43 | return contents; 44 | } 45 | } 46 | 47 | module.exports = function() { 48 | if(!contentService){ 49 | contentService = new ContentService(); 50 | } 51 | return contentService; 52 | } -------------------------------------------------------------------------------- /6/cpu/service/content.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../core/apiCenter'); 2 | 3 | let contentService; 4 | 5 | class ContentService { 6 | async filterUserinfo(contents) { 7 | let userIds = []; 8 | contents.forEach(content => { 9 | if(content['user_id']){ 10 | userIds.push(content['user_id']); 11 | } 12 | }); 13 | if(userIds.length < 1){ 14 | return this._addUserinfo(contents); 15 | } 16 | 17 | let userinfos = await ApiCenter.callApi('http://127.0.0.1:5000/v1/userinfos', {user_ids: userIds.join(',')}); 18 | if(!userinfos || userinfos.length < 1) { 19 | return this._addUserinfo(contents); 20 | } 21 | 22 | let mapUserinfo = {}; 23 | userinfos.forEach(item => { 24 | if(userIds.includes(item.id)){ 25 | mapUserinfo[item.id] = item; 26 | } 27 | }); 28 | 29 | return this._addUserinfo(contents, mapUserinfo); 30 | } 31 | 32 | /** 33 | * 34 | * @desc 在 content 中增加 userinfo 35 | * @param {*} contents 36 | * @param {*} userinfo 37 | */ 38 | _addUserinfo(contents, mapUserinfo={}) { 39 | contents = contents.map(content => { 40 | content['user_info'] = mapUserinfo[content['user_id']] ? mapUserinfo[content['user_id']] : {}; 41 | return content; 42 | }); 43 | return contents; 44 | } 45 | } 46 | 47 | module.exports = function() { 48 | if(!contentService){ 49 | contentService = new ContentService(); 50 | } 51 | return contentService; 52 | } -------------------------------------------------------------------------------- /6/io/service/content.js: -------------------------------------------------------------------------------- 1 | const ApiCenter = require('../core/apiCenter'); 2 | 3 | let contentService; 4 | 5 | class ContentService { 6 | async filterUserinfo(contents) { 7 | let userIds = []; 8 | contents.forEach(content => { 9 | if(content['user_id']){ 10 | userIds.push(content['user_id']); 11 | } 12 | }); 13 | if(userIds.length < 1){ 14 | return this._addUserinfo(contents); 15 | } 16 | 17 | let userinfos = await ApiCenter.callApi('http://127.0.0.1:5000/v1/userinfos', {user_ids: userIds.join(',')}); 18 | if(!userinfos || userinfos.length < 1) { 19 | return this._addUserinfo(contents); 20 | } 21 | 22 | let mapUserinfo = {}; 23 | userinfos.forEach(item => { 24 | if(userIds.includes(item.id)){ 25 | mapUserinfo[item.id] = item; 26 | } 27 | }); 28 | 29 | return this._addUserinfo(contents, mapUserinfo); 30 | } 31 | 32 | /** 33 | * 34 | * @desc 在 content 中增加 userinfo 35 | * @param {*} contents 36 | * @param {*} userinfo 37 | */ 38 | _addUserinfo(contents, mapUserinfo={}) { 39 | contents = contents.map(content => { 40 | content['user_info'] = mapUserinfo[content['user_id']] ? mapUserinfo[content['user_id']] : {}; 41 | return content; 42 | }); 43 | return contents; 44 | } 45 | } 46 | 47 | module.exports = function() { 48 | if(!contentService){ 49 | contentService = new ContentService(); 50 | } 51 | return contentService; 52 | } --------------------------------------------------------------------------------