node.js: using a function in several modules

I am trying to define a function, which can be used in all parts of my program. The program consists of several files with code, and I define the function in the first part like this:

file 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
});

file 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;

The important part is the function "debug" which I am using to log my results. I was using console.log before with some small changes like this:

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');
};

and it worked fine in every part of the program, so why doesnt the other (similar) function work? Is it because console.log was already defined before (by default)?

Yes. debug is not defined anywhere in file 2, so it does not work in file 2.

You can use events, this is a example from cordova code:

//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: The code is not tested but must work, with little fixs. The main strategy es call the function by the event library.

I think you'll want to take a look at: http://nodejs.org/api/modules.html

To access the debug function from other files, you'll want to expose your debug function in module.exports

In file1 (lets call it debug.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
});

module.exports = {
   debug: debug
}

Then in file2:

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;