Sam Dutton
Sam Dutton

Reputation: 15279

Node.js: how to serve /index.html for all URLs?

I'm using Node.js and I'd like to serve /index.html for all URLs.

For example, I'd like to serve /index.html for all these:

foo.com
foo.com/index.html
foo.com/bling
foo.com/blah/index.html

If possible I'd prefer not to change the URL displayed by the browser.

Is this possible and, if so, what's the best way to do it?

Upvotes: 1

Views: 2612

Answers (2)

atondelier
atondelier

Reputation: 2434

Without express, and if it's the only task your server has to do, you might use the fs module in your http server instance main callback, piping a readStream to the response this way:

http.createServer(function(request, response) {
    fs.createReadStream('index.html', {
        'bufferSize': 4*1024
    }).pipe(response);
});

Upvotes: 0

zavg
zavg

Reputation: 11071

You can use, for example, express.js MVC npm module

var express = require('express');
var app = express();

app.all('*', function(req, res){
  res.sendfile("index.html");
});

app.listen(3000);

Upvotes: 2

Related Questions