Last active
November 30, 2017 00:32
-
-
Save edavis25/6b6e092848ae742a2ca8bed3924d5ad0 to your computer and use it in GitHub Desktop.
Simple Express server to serve static files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
| Super simple Express server for serving files | |
| Note: Don't forget to npm install express! | |
*/ | |
const express = require('express'); | |
const app = express(); | |
const path = require('path'); | |
/* | |
| Send index file on root visit. | |
| Note: By default this code will serve an 'index.html' | |
| file in the same (root) directory as the server. | |
*/ | |
app.get('/', function(req, res) { | |
res.sendFile(path.join(__dirname, 'index.html')); | |
}); | |
/* | |
| Make additional static files available (ex: css/js files, etc). | |
| Note: This setup will use all files in the root directory. | |
| Since this might not be secure/desirable, it might be best to | |
| create a new directory (ie. public) and append to "__dirname". | |
| | |
| The first param ('/') is how the static files are reached in | |
| href/src tags. (ex: '/' = <script src="scripts.js"> in a view) | |
| | |
| If this 1st param is changed to something like "public" (instead of '/'), | |
| static files would be accessed by: <script src="public/scripts.js"> in a view | |
*/ | |
app.use('/', express.static(__dirname)); | |
// Listen to port 3000 | |
app.listen(3000, function() { | |
console.log('Come with me to port 3000 if you want to live'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment