Skip to content

Instantly share code, notes, and snippets.

@lxe
Last active December 29, 2015 08:59
Show Gist options
  • Save lxe/7647312 to your computer and use it in GitHub Desktop.
Save lxe/7647312 to your computer and use it in GitHub Desktop.

How to build a node.js site

Prerequisites:

General tools and skills:

  • Have a computer.
  • Be familiar with JavaScript, HTML, CSS.
  • Be familiar with a terminal. If you're on windows, PowerShell will probably do, but I have had great success with cygwin and console.
  • Be familiar with a text editor in which you can adjust automatic indentation and line endings. Vi/vim, Sublime Text or Notepad++ will do. Use an indent of 2 spaces and UNIX-style line endings.

Software you will need:

  • node. I suggest downloading it directly from the site. You can get it from your OS's package maintainer, but oftentimes the versions are lagging behind. More on that later.
  • git. You can grab it from your package maintainer, but it is also safe to download it directly from the website.

Get started

I usually make a directory called devel where I store all the things that you you develop or compile. I recommend doing this to keep you organized.

mkdir ~/devel; cd ~/devel
  1. Start your project by creating another directory called hello inside devel.
mkdir hello
cd hello
  1. Now, initialize a git repository in hello. This will create a .git directory which will keep the repository state.
git init
  1. Create a .gitignore file with the following contents to prevent committing temoprary files and node modules into the repository:
.DS_Store
node_modules
npm-debug.log
  1. Initialize your project as an npm package to track and save dependencies.
npm init

Enter version/author info if desired, but it's OK to just press enter at each prompt.

  1. You should now have the following files/directories in your project directory:
.
├── .git
├── .gitignore
└── package.json

1 directory, 2 files

Make a web server.

We are going to be using express, which is a widely-used framework that allows for easy creation of web servers.

  1. Install express through npm. The --save flag tells npm to add express to the dependency list in package.json
npm install --save express
  1. Create a file called app.js with the following content:
var express = require('express')
  , app  = express()
  , port = 3000;

app.get('/', function (req, res) {
  res.send('Hello World');
});

app.listen(port, function () {
  console.log('Server running at %d', port);
});
  1. Run your server:
node app
  1. See it in action by navigating to http://localhost:3000 in your browser:

  1. If everything works, commit your changes to the git repository!
git commit -am "initial commit"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment