Reputation: 9092
I'm building a NodeJS game engine. When the user creates an instance of the engine they must pass it an existing http server. The engine then attaches a socket server for updating the client side views.
What I'd like to do is serve a single JavaScript file at a special url that bridges the client side and allows the engine to setup its own sockets and provide the web page with a viewport and control binding api.
Is there anyway to add a request handler to an existing http server that can serve a single javascript based on the url?
I've tried this
function bindCoreFileServe(httpServer) {
//create a server
httpServer.on('request', function(req, res) {
//check the url
if(req.url === '/SliverJet.js') {
//send the datafunction (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}
});
}
But it crashes node because the existing server also tries to send its own headers.
Thanks.
Upvotes: 1
Views: 208
Reputation: 12379
The solution that worked for me looks like this:
function bindFileCoreServer (httpServer) {
httpServer.addListener('request', function (req, res) {
if (req.url === '/SliverJet.js') {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end('//Hello world!');
}
});
};
This is much simpler than storing the request listeners, replacing them, and then calling them in a loop if needed.
Upvotes: 0
Reputation: 9092
I figured this out via the source of socket.io. Essentially I detach all of the event listeners from the httpServer and store them in an array then I bind my own listener to it. If the url doesn't belong to me I execute all of the detached event listeners with their call method passing it the httpServer as the scope.
Upvotes: 1
Reputation: 63653
I don't think you can achieve that (attach 2 request handlers on the httpServer), but I suggest you take a different approach on this one.
For example, store all those URLs into the database and check for them using a wildcard, like so (this is for Express, but you get the idea):
app.get('/:db_url', function(req, res) {
get_url_from_database(req.params.db_url, function (url, error) {
if (error) { throw error; }
else {
// do things
}
});
});
Upvotes: 0