During web-app development, I usually need an easy way to serve my app locally. To do this I’ll either work off of a remote server or I will serve the files locally. In the past I would have used a LAMP package for this — but since I started using a Node+Express server to host the files I’ve never looked back.
Here’s a quick tutorial for anyone coming from LAMP wanting to try out Node/Express…
Go here, do that…
Next you’ll want to install express.js, this is the goto framework for making web services with Node.
We will add Node+Express resources in parallel with our app’s root directory. IOW: Navigate to the root directory of your app, then navigate up one directory.
In my case it’s
$ cd ~/Sites/
In that directory, add a file called
package.json with the following contents
"description": "express app that serves index.html",
In that same directory, run
$ npm install
Node will look at
package.json and download everything you need into
Finally, for the server app. Create a file called
server.js with the following contents…
express = require('express')
,app = express()
,_ = require('underscore')
,util = require('util')
,os = require('os');
rootDir = __dirname + '/app'
,port = 3000;
console.log('Serving files from: '+rootDir)
console.log('Listening on: ' + getAddresses() + ':' + port + '');
console.log('Press Ctrl + C to stop.');
interfaces = os.networkInterfaces(),
addresses = ;
if (address.family == 'IPv4' && !address.internal) addresses.push(address.address);
Start the server by entering
$ node server.js and you should see…
$ node server.js
Listening on 10.0.0.23:3000
Press Ctrl + C to stop.
That should do it. Now my URL looks like this…
…and I can test the project on other local devices with the url that displays in the console.