Sunday, January 29, 2017

node.js and express for dummies (1)

I've been looking for tutorials on the internet about node.js for beginners. The very basic steps in order to start doing something like "Hello World" are described below. Note that I am a completely dummy in this subject, so maybe there is something missing. A reminder to myself: please do update this post in the future.

Working on Arch Linux


1 - install node.js and npm from official repository:

# pacman -S nodejs


2 - install some kind of text editor, for example visual studio code available from user repository (AUR):

# yaourt -S visual-studio-code


3 - create a directory to hold a test application e.g. myapp and and make that the working directory:

# mkdir ~/Projects/myapp
# cd ~/Projects/myapp


4 - use the below command to create a package.json file for the application. You can accept all suggested options, including the entry point index.js

# npm init


5 - install express in the myapp directory and save it in the dependencies list as per below:

# npm install express --save


6 - sample code for index.js as per below:

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!')
})


7 - run the myapp with the following command and then load http://localhost:3000/ in a browser to see the output.

# node index.js


8 - in order to make the things a bit more complicated, let's use the express app generator which creates a skeleton for some advanced apps. The express-generator package installs the express command-line tool:

# npm install express-generator -g


9 - create an express app named myapp2 in the current working directory:

# cd ~/Projects
# express --view=<jade|ejs> myapp2 


10 - at last, install dependencies

# cd myapp2
# npm install


11 - the newly created app can be run with the below command:

# npm start
or in debug mode
# DEBUG=myapp:* npm start

the npm start looks into the package.json what is under "scripts" / "start" to start up the app. e.g.:

  "scripts": {
    "start": "node ./bin/www"
  },



Well, there is still a lot to come.



References: 

2 comments: