user124114 user124114 - 2 months ago 14
Node.js Question

static files with express.js

I want to serve

index.html
and
/media
subdirectory as static files. The index file should be served both at
/index.html
and
/
URLs.

I have

web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));


but the second line apparently serves the entire
__dirname
, including all files in it (not just
index.html
and
media
), which I don't want.

I also tried

web_server.use("/", express.static(__dirname + '/index.html'));


but accessing the base URL
/
then leads to a request to
web_server/index.html/index.html
(double
index.html
component), which of course fails.

Any ideas?




By the way, I could find absolutely no documentation in Express on this topic (
static()
+ its params)... frustrating. A doc link is also welcome.

abe abe
Answer

express.static() expects the first parameter to be a path, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.

Serving static files in Express documentation.