user1318416
user1318416

Reputation: 759

Default Folder Functionality for Node.JS

I would like to add some real-time functionality to my website with node.js and socket.io, but not have to deal with the hassle of page requests/responses. Can I get the normal folder functionality, where it serves index.html first and then loads any js/css dependencies automatically?

Thanks!

Upvotes: 2

Views: 9038

Answers (3)

James Gentes
James Gentes

Reputation: 8086

I used a slightly different approach with the same result:

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

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

app.listen(process.env.PORT || 3000);

Upvotes: 1

patalmypal
patalmypal

Reputation: 6712

If you only wish to serve static files, it's quite simple using express.

The app.js file need have only the following lines of code

    var express = require('express');

    var app = express.createServer(
       express.static(__dirname + '/public')
       );

    app.listen(3000);

Place all your html, css, javascript files is a 'public' folder at the root of your application. So a typical app folder would look like this:

  app.js
  /public
     index.html
     reset.html
     ...
     ...
     /css
        main.css
        reset.css
        ...
        ...
     /js
        header.js
        util.js
        ...
        ...

Upvotes: 2

Mustafa
Mustafa

Reputation: 10413

You can use Express framework. Place your files under public folder, all your styles, javascript files, other HTML files. You only need to give express an entry point, so It can give the client index.html.

    var fs = require("fs");
    var express = require("express");
    app = express.createServer();

    app.use(express.static(__dirname + '/public'));
    app.get('/', function(req, res) {
        fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, text){
            res.send(text);
        });
    });
    app.listen(3000);

Upvotes: 7

Related Questions