我想要定義一個函數,它可以在我的程序的所有部分中使用。該計劃包括與代碼的幾個文件,我在第一部分定義函數是這樣的: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(默認情況下)?