2014-07-18 33 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;