- Create a new folder, and go into it.
123mkdir simple-websitecd simple-website
- Initialize a new Node project within the folder.
12npm init
- Fill out the info it asks you for. In most cases, the defaults will be fine. This will create a package.json file in the folder.
-
We are going to install a package called Express. It lets us get websites up and running quickly and easily.
12npm install --save express - Additionally, we are going to install Pug, an HTML template language.
12npm i -S pug
- Install nodemon, a program that watches your Node application during development, and restarts the server any time there are changes.
12npm i -g nodemon
- In your package.json, replace the contents of
"scripts"
with these commands.12345{"watch": "nodemon server.js -e js,pug", // runs nodemon to watch for server updates"start": "node server.js" // runs the server without nodemon} - Make a new file called server.js, and paste in the following code:
123456789101112131415161718192021// require all dependenciesvar express = require('express');var app = express();// set up the template engineapp.set('views', './views');app.set('view engine', 'pug');// GET response for '/'app.get('/', function (req, res) {// render the 'index' template, and pass in a few variablesres.render('index', { title: 'Hey', message: 'Hello there!' });});// start up the serverapp.listen(3000, function () {console.log('Listening on http://localhost:3000');});
- Make a new folder called views, and within it make a new file called index.pug. In that file, paste the following code:
123456htmlheadtitle= titlebodyh1= message
- Start up your server with
12npm run watch
- In your browser, go to http://localhost:3000 to view your site. Try making changes to server.js and reloading the webpage to see it change.
-
All of the above steps are hard to remember, and don’t give you a ton of functionality out of the box. Let’s use the default Express Generator to make a better web app, much more quickly. First, install Express Generator with
12npm install express-generator -g - Next, create a new project with the generator.
12express --view=pug --git MyAppName
cd
into the newly create folder,npm install
inside of it, then open the folder in Sublime Text or similar and look around. What parts are similar and what parts are different from the simple app you made?-
Start the server, and visit it at
http://localhost:3000
12npm start -
Next steps — Try adding functionality to the site:
- Add CSS stylesheets to layout and style the page
- Pass useful data from the server to the client (not just a static “Hello there!”)
- Add client-side Javascript to add dynamic elements to the page (D3.js is a great way to make data visualizations)
- Integrate Socket.io on the server and client to pass data back and forth and between clients