我是Node.js域名的新手,我正在试验它们。我试图让mainDomain
在数据库上显示成功的消息。现在,当我开始express.js
时,没有错误,一切正常。但是,在成功建立数据库连接后,消息不会显示:
db.js:
var mongoose = require( 'mongoose' );
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter();
function connectDatabase() {
var dbURI = 'mongodb://localhost/database';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
ee.emit('message', 1, 2, 3);
// console.log('Mongoose default connection open to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through' +
' app termination');
process.exit(0);
});
});
}
module.exports.connectDatabase = connectDatabase;
app.js:
var express = require('express');
var morgan = require('morgan');
var fs = require("fs");
var createDomain = require("domain").create;
var app = express();
app.use(morgan('dev'));
app.use(express.static(__dirname + '/app/static/views'));
app.use(express.static(__dirname + '/app/static'));
app.use(express.static(__dirname + '/app/images'));
app.use(express.static(__dirname + '/app'));
var apiScript = require('./app/scripts/api_scripts/call_all_api.js');
var db = require(__dirname + '/app/data/db.js');
var mainDomain = new createDomain();
mainDomain.run(function () {
db.connectDatabase();
mainDomain.on('message', function(msg) {
console.log('yoyoyoyo');
});
});
mainDomain.run(function () {
mainDomain.on('error', function(er) {
console.log('error, but oh well', er.message);
});
var server = app.listen(9000, function() {
console.log('Listening on port %d', server.address().port);
});
});
更新:如果我ee.emit('error')
而不是ee.emit('message', 1, 2, 3);
,我可以抓住它。我不明白为什么我不能发出ee.emit('message');
答案 0 :(得分:0)
您需要替换这些行:
mainDomain.on('message', function(msg) {
console.log('yoyoyoyo');
});
关于他们
db.on('message', function(msg) {
console.log('yoyoyoyo');
});