1

I'm writing a 2d game using the impact engine and socket IO. I decided to use express as well for the website itself.

Impact requries me to serve about a dozen files (js, css and images) from multiple directories.

How can I serve these using express?

Thanks in advance.

Petter Thowsen
  • 1,697
  • 1
  • 19
  • 24

2 Answers2

1

Here's an example, "./public" takes precedence over the others:

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

But I would suggest you putting all files under one directory (vis softlink) and only serve one static folder.

Tony Chen
  • 1,804
  • 12
  • 13
1

There's middleware that Express inherits from Connect, which is known as static(). The function starts a static file server that mounts to a specified path.

// serve files from /static to path /
app.use('/', express.static(__dirname + '/static'));

// server files from /stylesheets to /css
app.use('/css', express.static(__dirname + '/stylesheets'));

A middleware function is a function that runs each time Express receives a request. The static file server will detect if a file exists, and will also detect its MIME type. Therefore stylesheets will be served as stylesheets, scripts as scripts, etc.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162