Steps to create Beginning Project

STEP 1: create directory and call npm install and follow instructions

$ mkdir myapp  $ cd myapp  

Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init  

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)  

Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.

 

RESULTS -- file package.json created (note I created app.js previously)

 

package.json = tells dependencies of application

file example (hello world example from scratch):
{
"name": "helloworld",
"version": "1.0.0",
"description": "simple hello world app",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "L. Grewe",
"license": "ISC",
"dependencies": {
"express": "^4.14.1"
}
}

DIFFERENT EXAMPLE (from Heroku getting started example):

{
"name": "node-js-getting-started",
"version": "0.2.5",
"description": "A sample Node.js app using Express 4",
"engines": {
"node": "5.9.1"
},
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"pg": "4.x",
"cool-ascii-faces": "1.3.4",
"ejs": "2.4.1",
"express": "^4.13.3"
},
"repository": {
"type": "git",
"url": "https://github.com/heroku/node-js-getting-started"
},
"keywords": [
"node",
"heroku",
"express"
],
"license": "MIT"
}

 

 

STEP 2: install Express (if you want it, most will)and any other dependencies needed

Now install Express in the myapp directory and save it in the dependencies list. For example:

$ npm install express --save  

 

RESULTS

Expanded Express Directory structure

STEP 3: create your application code (app.js or index.js or whatever) --this is using the Express framework

 create a file named app.js and here is some SIMPLE hello world code --do whatever YOU want

var express = require('express')
  var app = express()
    app.get('/', function (req, res) {
    res.send('Hello World!')
  })

    app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
  })

The app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

The req (request) and res (response) are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback), and anything else you would do without Express involved.

 

STEP 4: run your code (say called app.js as above)

Run the app with the following command:

$ node app.js  

Then, load http://localhost:3000/ in a browser to see the output.


 

© Lynne Grewe