Serve static files with ExpressJS

0
3039
NodeJS & ExpressJS
NodeJS & ExpressJS

Serving static files is one of very basic techniques when working with NodeJS and ExpressJS. For anyone who doesn’t know about it, or want to create your own server to serve your static files, such as HTML, JS, CSS... while developing front-end; this guide is for you.

Make sure you have NodeJS and NPM being ready on your machine, let’s setting up by grabbing express,

$ npm install express

Create a file for server code,

$ touch app.js

Following is the code for the app,


var express = require('express');
var app = express();
var path = require('path');
// serve all static files on 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, function () {
    console.log('server started to listening');
});

as you see, the code is very simple and will help to serve all static files in public/ directory, try it on,

$ node app.js

Open browser at http://localhost:3000; it will error, because we haven’t created the public/ directory. Let’s create the public/ directory along with a static file, index.html with very simple content.

<h1>Hello World</h1>

Try to run server again and see result in browser. Let’s tweak it a bit. We can change port instead of hard-coded port value,


var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, function () {
    console.log('server started to listening');
});

When running server, we can pass the port number via PORT environment variable,

$ PORT=9000 node app.js

You can also allow input to specify the directory to serve,


var express = require('express');
var app = express();
var path = require('path');
var port = process.env.PORT || 3000;
var serveDir = process.env.SERVE_DIR || path.join(__dirname, 'public');
app.use(express.static(serveDir));
app.listen(port, function () {
    console.log('server started to listening');
});

So you can input the serve directory as SERVE_DIR environment variable.

You can do even more by making it a command utility for global usage, but it will not be covered in this guide.