If I understand correctly, the problem seems to be this: You want to access the
result of an asynchronous function (the HTTP request) in other modules. However,
Node's require()
is synchronous; there is no asynchronous require()
. There
are a few solutions to this, none of which will be unfamiliar if you know
JavaScript.
The simplest solution is to wrap your server.js module in a function that takes
a callback. Then, call the callback once the request is available, like so:
// server.js
'use strict';
// ...
module.exports = function(callback) {
// ...
http.createServer((req, res) => {
req.body = '';
// Call end with error on error
req.on('error', err => res.end(err));
// Append chunks to body
req.on('data', chunk => req.body += chunk);
// Call callback here
req.on('end', err => {
// Call with error as first argument on error
if (err) callback(err);
// Call with request as second argument on success
else callback(null, req);
});
}).listen(/*...*/);
// ...
};
And in your test.js file:
// test.js
'use strict';
const server = require('./server');
// Do something with the request here.
server((err, req) => {
if (err) console.error(err);
else console.log(req.headers);
});
There is a problem with this approach. Every time you want to access the
request, your server function will run all over again. What if you want to run
the server once and then have access to the request as many times as you want?
Consider using Node's events
module for this. In your server.js file, you can
export an EventEmitter instance instead of a function. Emit appropriate events
in that module, and then you can add listeners in any other module that needs
access to the request. Your server.js file will look something like this:
// server.js
'use strict';
const EventEmitter = require('events');
const emitter = new EventEmitter();
// ...
http.createServer((req, res) => {
req.body = '';
req.on('error', err => res.end(err));
req.on('data', chunk => req.body += chunk);
// Emit events here:
req.on('end', err => {
// Emit 'error' event on error.
if (err) emitter.emit('error', err);
// Emit 'data' event on success.
else emitter.emit('data', req);
});
}).listen(/*...*/);
// ...
module.exports = emitter;
And in your test.js file:
// test.js
'use strict';
const server = require('./server');
// Do something on error event.
server.on('error', console.error);
// Do something on data event.
server.on('data', req => {
console.log(req.headers);
});