Skip to content

Instantly share code, notes, and snippets.

@rsj217
Last active August 29, 2015 14:00
Show Gist options
  • Save rsj217/83a53c4324dcbac2e091 to your computer and use it in GitHub Desktop.
Save rsj217/83a53c4324dcbac2e091 to your computer and use it in GitHub Desktop.
javascript coder gist
var cluster = require('cluster');
if (cluster.isMaster) {
/* var cpu_count = require('os').cpus().length;
require('os').cpus().forEach(function() {
cluster.fork();
});*/
var cpu_count = 2;
for (var i = 0; i < cpu_count; i++){
cluster.fork();
}
cluster.on('listening', function(worker,address){
console.log('listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port);
});
cluster.on('exit', function (worker, code, signal) {
cluster.fork();
});
}else{
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
var RedisStore = require('connect-redis')(express);
var worker_id = 'Worker' + cluster.worker.id;
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
// 开发环境
app.configure('development', function(){
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(express.cookieParser('your secret here'));
app.use(express.session());
});
app.configure('production', function(){
var oneYear = 31557600000;
app.use(express.static(path.join(__dirname, 'public'), { maxAge: oneYear }));
app.use(express.cookieParser());
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
pass: 'RedisPASS'
}),
secret: '1234567890QWERTY'
}));
});
app.use(app.router);
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
console.log('development NODE_ENV:' + app.settings.env);
});
}
var cluster = require('cluster');
if (cluster.isMaster) {
var cpu_count = 2;
for (var i = 0; i < cpu_count; i++){
cluster.fork();
}
cluster.on('listening', function(worker,address){
console.log('listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port);
});
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
} else {
var worker_id = 'Worker' + cluster.worker.id;
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello work'));
});
http.createServer(app).listen(3000, function() {
console.log('Express app started by %s', worker_id);
});
}
var cluster = require('cluster');
if (cluster.isMaster) {
/* var os = require('os');
os.cpus().forEach(function() {
cluster.fork();
});*/
var cpu_count = 2;
for (var i = 0; i < cpu_count; i++){
cluster.fork();
}
cluster.on('listening', function(worker,address){
console.log('listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port);
});
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
} else {
var worker_id = 'Worker' + cluster.worker.id;
var http = require('http');
// Start the app
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('hello world');
res.end();
}).listen(3000, function() {
console.log('Express app started by %s', worker_id);
});
}
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database : 'nodejs'
});
connection.query('SELECT * FROM dt_user', function (err, rows) {
if(err) throw err;
console.log(rows);
});
connection.end(function (err) {
console.log('mysql close successful');
});
/**
* @type class BaseModel
* @author rsj217
* @time 2014-05-08
* @desc desc base_model.js
*/
var Util = require('./util');
var mysql = require('mysql')
var dbClient;
module.exports = function () {
__constructor();
/*
* @desc 根据主键值对查询单条记录
* @param tableName string
* @param idJson id
* @param callback function
* @return null
*/
this.findOneById = function (tableName, idJson, callback) {
dbClient.query('SELECT * FROM ' + tableName + ' WHERE ?', idJson, function (err, results) {
if (err) {
console.log('Get Date Error:' + err.message);
dbClient.end();
callback(false);
} else {
if (results){
callback(results.pop());
}else{
callback(results);
}
}
});
dbClient.end(function (err) {
console.log('mysql close successful');
});
};
/*
*@desc 插入数据
*@param tableName string
*@param rowInfo json
*@param callback function
*/
this.insert = function (tableName, rowInfo, callback) {
dbClient.query('INSERT INTO ' + tableName + ' SET ?', rowInfo, function (err, result) {
if (err) throw err;
callback(result.insertId)
});
dbClient.end(function (err) {
console.log('mysql close successful');
});
};
/*
* @desc 修改数据库一条记录
* @param tableName string
* @param idJson json
* @param rowInfo json
* @param callback function
* @return null
*/
this.modify = function (tableName, rowInfo, idJson, callback) {
dbClient.query('UPDATE ' + tableName + ' SET ? WHERE ?', [rowInfo, idJson], function(err, result){
if (err) {
console.log('Get Date Error:' + err.message);
dbClient.end();
callback(false);
}else{
callback(result);
}
});
dbClient.end(function (err) {
console.log('mysql close successful');
});
};
/*
* @desc 删除数据库记录
* @param tableName string
* @param idJson json
* @param rowInfo json
* @param callback function
* @return null
*/
this.remove = function (tableName, idJson, callback) {
dbClient.query('DELETE FROM ' + tableName + ' WHERE ?', idJson, function(err, result){
if (err) {
console.log('Get Date Error:' + err.message);
dbClient.end();
callback(false);
}else{
callback(result);
}
});
dbClient.end(function (err) {
console.log('mysql close successful');
});
};
/*
* @desc 条件查询
* @param tableName string
* @param whereJson json
* @param orderByJson json
* @param callback function
* @return null
*/
this.find = function (tableName, whereJson, orderByJson, limitArr, fieldsArr, callback) {
var andWhere = whereJson['and'],
orWhere = whereJson['or'],
andArr = [],
orArr = [];
for (var i = 0; i < andWhere.length; i++) {
andArr.push(andWhere[i]['key'] + andWhere[i]['opts'] + andWhere[i]['value']);
};
for (var i = 0; i < orWhere.length; i++) {
orArr.push(orWhere[i]['key'] + orWhere[i]['opts'] + orWhere[i]['value']);
};
var fieldsStr = fieldsArr.length > 0 ? fieldsArr.join(',') : '*',
andStr = andArr.length > 0 ? andArr.join(' and ') : '*',
orStr = orArr.length > 0 ? ' or ' + orArr.join(' or ') : '*',
limitStr = limitArr.length > 0 ? 'limit ' + limitArr.join(',') : '',
orderStr = orderByJson ? ' order by ' + orderByJson['key'] + ' ' + orderByJson['type'] : '';
var sql = 'SELECT ' + fieldsStr + ' FROM ' + tableName + ' WHERE ' + andStr + orStr + orderStr + ' ' + limitStr;
console.log(sql)
dbClient.query(sql, function(err, result){
if (err) {
console.log('Get Date Error:' + err.message);
dbClient.end();
callback(false);
}else{
callback(result);
}
});
dbClient.end(function (err) {
console.log('mysql close successful');
});
};
function __constructor () {
// 读文件的形式
// var dbConfig = Util.get('config.json', 'db');
// 模块的方式
var dbConfig = require('./config.json')['db'];
client = {};
client.host = dbConfig['host'];
client.port = dbConfig['port'];
client.user = dbConfig['user'];
client.password = dbConfig['password'];
dbClient = mysql.createConnection(client);
dbClient.connect();
dbClient.query('USE ' + dbConfig['database'], function(error, result){
if (error) {
console.log('ClinetConnectionReady Error' + error.message);
dbClient.end();
}
console.log('connection local mysql success');
});
};
}
//配置文件
//config.json
{
"db" : {
"host" : "localhost",
"port" : "3306",
"user" : "root",
"password" : "",
"database" : "nodejs"
}
}
//入口
//index.js
var BaseModel = require('./base_model.js');
var baseModel = new BaseModel();
var rowInfo = {};
var tableName = 'node_book';
rowInfo.book_name = 'nodejs book';
rowInfo.author = 'rsj217';
baseModel.insert('node_book', rowInfo, function (ret) {
console.log(ret);
});
var idJson = {'book_id': 1};
baseModel.findOneById(tableName, idJson, function (ret) {
console.log(ret);
});
var newInfo = {};
newInfo.book_name = 'new book';
newInfo.author = 'rsj217';
var idJson = {'book_id': 2};
baseModel.modify(tableName, newInfo, idJson, function(ret){
console.log(ret);
});
var idJson = {'book_id': 4}
baseModel.remove(tableName, idJson, function(ret){
console.log(ret);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment