I’ve been talking to a few people lately about how I build web applications. There’s no single right-way of doing it, but here’s my workflow, split into small blog posts you can follow.
First of all, let’s create a web server using node.js.
As a prerequisite, install node.js. You can download the latest version here.
You’ll also need somewhere on your computer to save the files you’re going to create. Using your console, navigate to the correct place, and create a directory:
If you’re planning on using git, you can also create a
.gitignorefile. Just add
node_modulesto the ignore list.
Express is a framework which makes it easy to write web servers in node.
To install express, you just need to type:
You’ll notice that a
node_modules directory is created, with an
express sub-directory. This contains all the express code, as well as its dependencies.
Now let’s create a basic web server and start listening on port 8080 for web requests.
Some things to note about what we’ve written:
- The express package can be used to create multiple web servers listening on different ports, which is why we need to call
express()to create an instance of an application.
- We call
app.get(...)to register a route that listens to GET requests that match the supplied path. You can also call
- When registering a route, you supply a function which gets called every time a matching request is received. The function should have
resarguments, which represent the request and response data respectively.
- You must tell the application which port to listen on to start the web server.
Let’s fire up the application, and make sure it works. To do this, call node, passing our script file as the first argument:
Now point your browser to
http://localhost:8080/ and you should see
It is a good idea to create a
package.json file. Its not necessary, but its useful for keeping track of the packages your application uses.
To create one, run:
You can just go with all the default options, or set the values if you want.
You can run
npm initat any point, it’ll figure out what packages you’ve already included.
This will create a
When adding further packages, if you add the
--save option, npm updates the
package.json file so it keeps it up to date. i.e.
package.json file (without copying all the packages in
node_modules directory). You can then run
npm install to restore all the modules in one go.