March 26, 2021

Getting Started with NPM and Simple Express Web App

Prerequisite

Install Node.js and NPM. See https://magnus-k-karlsson.blogspot.com/2021/03/how-to-install-nodejs-on-fedora-33.html.

Create new Project with NPM

$ mkdir chapter1; cd chapter1

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (chapter1) 
version: (1.0.0) 
description: Simple Express Web App
git repository: 
author: Magnus K Karlsson
license: (ISC) 
About to write to /home/magnuskkarlsson/WebstormProjects/Nodde.js_from_Ground_Up_for_Beginners/chapter1/package.json:

{
  "name": "chapter1",
  "version": "1.0.0",
  "description": "Simple Express Web App",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Magnus K Karlsson",
  "license": "ISC"
}


Is this OK? (yes) yes

Add Express NPM package

All NPM package can be search at https://www.npmjs.com/ and Express can be found at https://www.npmjs.com/package/express.

$ npm install express

$ cat package.json
{
  "name": "chapter1",
  "version": "1.0.0",
  "description": "Simple Express Web App",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Magnus K Karlsson",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Now lets write a simple Express web app.

$ vi server.js
const express = require('express')
const app = express()

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

app.listen(3000)

And to run and test it.

$ node server.js

$ curl localhost:3000
Hello World

No comments: