Getting Started with Node.js
12 Apr 2016Getting Node.js
There are different ways of getting Node.js:
- Downloading installers or binaries
- https://nodejs.org/en/download/
- Build from source code
- For OSX and Linux environment, manage multiple version using
nvmtool- We will be installing Node.js using the
nvmtool for OSX
- We will be installing Node.js using the
Installing Node Version Manager nvm tool
- Manual install of nvm:
$ git clone https://github.com/creationix/nvm.git ~/nvm
- Use
sourcecommand load function file(nvm.sh) into the command prompt:
$ . ~/nvm/nvm.sh
- Test nvm:
$ nvm
Installing Node.js using nvm tool
- Install multiple versions of node:
$ nvm install v4.4.2
$ nvm install v5.10.1
- List installed node versions:
$ nvm ls
- Display current version:
$ node -v
- Switch node version:
$ nvm use v4.2.2
- Set Alias default:
$ nvm alias default v5.10.1
- Run node (Enters REPL[Read Eval Print Loop] Terminal):
$ node
> console.log("Node Intro");
Hello World
undefined
>
(^C again to quit)
>
##
Running a simple web server
-
Create a
server.jsfileconst http = require('http'); const hostname = '127.0.0.1'; const port = 1337; http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Node Intro\n'); }).listen(port, hostname, () => { console.log('Server running at http://${hostname}:${port}/'); }); - Then run
$ node server.js - Open
http://127.0.0.1:1337in browser to test your simple web server