Hello world! That is the goal of this module of your express.js tutorial 2019.
If you do not have npm and node installed please checkout nodejs.org's official downloads to get the required software.
To test your installation please run the following in your shell of choice:
node --version
# It should print v10.8.0 or similiar
npm --version
# It should print 6.9.0 or similiar
Perfect! With node/npm installed we are ready to get started! :)
Installing Express.Js
Now you should create a project folder on your file system.
mkdir express-project-2019
cd express-project-2019
Your current working directory is express-project-2019
. Now we'll run
npm to get our project started.
npm init --yes
Because this is a practice project we don't need to configure all the options. But if you need to you can configure package.json options here.
With a package.json file npm commands will install modules locally which is exactly what you need.
You are ready to install express.js.
npm install express --save
--save
adds the express package to your package.json file. With your
version of npm (>6), we will also get a snapshot file called
package-lock.json. Package Lock is great because it captures all of the
dependency versions so another blank install gets the correct versions.
Express.js Hello World
With express installed we can get started with our hello world app!
Open up a text editor with index.js
. If you need a text editor I
recommend https://atom.io/ for mac and Notepade Plus Plus for Windows.
Here is what the contents of index.js
should be. I'll comment the code
for you so you know what each line does and why it is necessary.
// Require application dependencies
const express = require('express');
// Create our app by calling the express function
const app = express();
// Register a route handler for GET requests made to /hello
app.get('/hello', (req, res) => {
res.send('hello world');
});
// Get port from environment or default to port 3000.
const port = process.env.PORT || 3000;
// Ask our app to listen on the calculated port.
app.listen(port, () => {
console.log(`Successfully express js server listening on port ${port}`);
});
You should run this with:
node index.js
# or with custom PORT
PORT=54321 node index.js
In a separate terminal tab/window or browser window visit http://localhost:3000/hello. Or replace 3000 with the custom port used.
$ curl http://localhost:3000/hello
$ hello world%
Congratulations! You just wrote a hello world app using express.js on the node js platform. From here you can go anywhere. Your tutorial continues with a closer look on express.js routing.