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): {
|
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
|
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.