Switch from node-static to express

179 Views Asked by At

I have a simple application running on node.js with websockets. This application uses the node-static module for serving some html pages with css, js and so on. The folder structure is this:

-app
    - index.html
    - server.js
    - img/
        - base.png
        - sub/
            - sub.png
    - scripts
        - base.js
        - sub/
            - sub.js
    - css
        - base.css
        - sub/
            - sub.css

Where server.js is the server file. Inside server.js there is the following code:

var static = require('node-static');
var http = require('http');
var file = new(static.Server)();

var app = http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(process.env.PORT || 1234);

var WebSocketServer = require('websocket').server;
new WebSocketServer({
  httpServer: app,
  autoAcceptConnections: false
}).on('request', onRequest);

...

Now I need to switch from node-static to Express because I need to use routes. I used this code, however it doesn't work:

var express = require('express');
var app = express();
var http = require('http');
var httpServer = http.Server(app);

app.use(express.static(__dirname+'/app'));

app.get('/', function(req, res){
    res.sendfile(__dirname + '/index.html');
});
app.listen(1234);

var WebSocketServer = require('websocket').server;
new WebSocketServer({
  httpServer: app,
  autoAcceptConnections: false
}).on('request', onRequest);

...

I can serve files, however it breaks the websocket connection. What's wrong? Please note that the solution should be suitable for working on localhost and Heroku.

1

There are 1 best solutions below

0
On BEST ANSWER

I resolved my problem using the following code:

var http = require("http");
var express = require("express");
var app = express();
var port = process.env.PORT || 1234;

app.use(express.static(__dirname + "/"));

var server = http.createServer(app);
server.listen(port);

console.log("http server listening on %d", port);

var WebSocketServer = require('websocket').server;
new WebSocketServer({
  httpServer: server,
  autoAcceptConnections: false
}).on('request', onRequest);

...

This code is derived from https://devcenter.heroku.com/articles/node-websockets, however my code use the 'websocket' node module instead of 'ws'. Thanks to @Tony for the hint.