adelura
adelura

Reputation: 556

Serve custom static files with socket.io nodejs

I try to share my code betwen server and client I use following code (app.js):

var io = require('socket.io').listen(8000), 
  Static = require('socket.io').Static; 

io.configure(function () {
  var _static = new Static(io); 

  // some methods to add my custom files 

  _static.add('\public\test.js');
  io.set('static', _static);
});

My file structure looks like this:

  1. root
    • app.js
    • public
      • test.js

When I type "http://localhost:8000/public.test.js" Browser download default file "Welcome to socket.io"

Upvotes: 3

Views: 3338

Answers (1)

cmbuckley
cmbuckley

Reputation: 42507

This question is rather old, but here's the current way to do it (for v0.9):

var io = require('socket.io').listen(8000);
io.static.add('/path/for/request.js', {file: 'path/to/file.js'});

Note that the path to the resource is relative to the socket.io path, so the request URI would be something like:

http://localhost:8000/socket.io/path/for/request.js

If you see an error like Protocol version not supported, then that means your request URI probably has an extension that the manager can't support. Here's how to add that support:

io.static.add('/path/for/request.foo', {
  mime: {
    type: 'application/javascript',
    encoding: 'utf8',
    gzip: true
  },
  file: 'path/to/file.js'
});

The documentation points at their own Static library for a working implementation.

Upvotes: 7

Related Questions