我正在设置一个新项目的结构,该项目将使用Node.js和Express构建.我正在使用HTML5 Boilerplate获得最佳起点.它附带了多种类型服务器的配置文件:Apache,Nginx,Node.js等.以下是HTML5 Boilerplate团队提供的Node.js服务器配置文件:
/* h5bp server-configs project
*
* maintainer: @xonecas
* contributors: @niftylettuce
*
* NOTES:
* compression: use the compress middleware provided by connect 2.x to enable gzip/deflate compression
* http://www.senchalabs.org/connect/compress.html
*
* concatenation: use on of the following middlewares to enable automatic concatenation of static assets
* - https://github.com/mape/connect-assetmanager
* - https://github.com/TrevorBurnham/connect-assets
*/
var h5bp = module.exports,
_http = require('http'),
_parse = require('url').parse;
// send the IE=Edge and chrome=1 headers for IE browsers …Run Code Online (Sandbox Code Playgroud) node-postgres声明如下:
node-postgres支持'事件发射器'样式API和'回调'样式.回调样式更简洁,通常更受欢迎,但是公平的API可以派上用场.它们可以混合搭配.
使用事件发射器API,我可以执行以下操作:
var db = new pg.Client("insert-postgres-connection-info");
db.connect();
Run Code Online (Sandbox Code Playgroud)
然后我可以使用db在我的网络应用程序中执行查询db.query('sql statement here').使用回调样式,每次我想运行查询时都会执行以下操作:
pg.connect(conString, function(err, client) {
client.query("sql statement", function(err, result) {
// do stuff
});
});
Run Code Online (Sandbox Code Playgroud)
所以我的问题是为什么使用回调样式"通常更喜欢"?每次使用数据库执行某些操作时打开连接效率不高吗?使用回调样式有什么好处?
编辑
我可能会错误地认为他的意思是"回调风格"(我不是在开玩笑,我的JavaScript不是很强)但我的问题是关于连接方法.我假设以下是回调样式连接方法:
// Simple, using built-in client pool
var pg = require('pg');
//or native libpq bindings
//var pg = require('pg').native
var conString = "tcp://postgres:1234@localhost/postgres";
//error handling omitted
pg.connect(conString, function(err, client) {
client.query("SELECT NOW() as when", function(err, result) {
console.log("Row count: %d",result.rows.length); // 1
console.log("Current year: %d", result.rows[0].when.getYear());
}); …Run Code Online (Sandbox Code Playgroud)