2014-07-18 34 views
0

我想要定义一个函数,它可以在我的程序的所有部分中使用。该计划包括与代码的几个文件,我在第一部分定义函数是这样的:node.js:在几个模块中使用函数

文件1:

var debug_log = fs.createWriteStream('./' + '/debug.log', {flags : 'w'}); 
var debug = function(d){ 
    debug_log.write(util.format(d) + '\n'); 
}; 

var part2 = require('./somefile.js'); 
part2.part2(function(result){ 
    //some work is done with the result 
}); 

文件2:

function part2(callback){ 
    //some work is done with initial data 
    debug('done'); //here is were I am trying to use the function 
    callback(data); 
} 
exports.part2 = part2; 

的重要组成部分,是函数“调试”,我正在使用它来记录我的结果。我使用的console.log之前,像这样的一些小变化:

var console_log = fs.createWriteStream('./' + '/console.log', {flags : 'w'}); 
var log_stdout = process.stdout; 
console.log = function(d){ 
    console_log.write(util.format(d) + '\n'); 
    log_stdout.write(util.format(d) + '\n'); 
}; 

,并在节目中的每一个部分工作正常,那么为什么犯规另一个(类似)功能的工作?是否因为之前已经定义了console.log(默认情况下)?

回答

0

是的。 debug没有在文件中的任何地方2定义,所以它不会在文件上工作2

0

您可以使用事件,这是从科尔多瓦代码示例:

//file_events.js 
module.exports = new (require('events').EventEmitter)(); 

//main.js 
var events = require('./file_events.js'); 

var debug_log = fs.createWriteStream('./' + '/debug.log', {flags : 'w'}); 
var debug = function(d){ 
    debug_log.write(util.format(d) + '\n'); 
}; 

var part2 = require('./somefile.js'); 
part2.part2(function(result){ 
    //some work is done with the result 
}); 

events.on("log", debug) 

//somefile.js 
var events = require('./file_events.js'); 

function part2(callback){ 
    //some work is done with initial data 
    events.emit('log', 'done'); //emit a event catched for the main file on 
    callback(data); 
} 
exports.part2 = part2; 

PD:代码没有进行测试但必须工作,几乎没有修复。主要策略是由事件库调用函数。

0

我想你会想看看: http://nodejs.org/api/modules.html

从其它文件访问调试功能,你要揭穿你的调试功能module.exports

在文件1在文件2然后

var debug_log = fs.createWriteStream('./' + '/debug.log', {flags : 'w'}); 
var debug = function(d){ 
    debug_log.write(util.format(d) + '\n'); 
}; 

var part2 = require('./somefile.js'); 
part2.part2(function(result){ 
    //some work is done with the result 
}); 

module.exports = { 
    debug: debug 
} 

::(让叫它debug.js)

var debug = require('./debug').debug; //assuming debug.js is in the same directory 

function part2(callback){ 
    //some work is done with initial data 
    debug('done'); //here is were I am trying to use the function 
    callback(data); 
} 
exports.part2 = part2;