Node.js

From 太極
Revision as of 19:14, 8 December 2017 by Brb (talk | contribs) (→‎Installation)
Jump to navigation Jump to search

Installation

See also my note on Javascript

Error from sudo apt-get install nodejs npm

The following packages have unmet dependencies:
  nodejs:  Conflicts: npm
E: Unable to correct problems, you have held broken packages.

Error from running npm

$ sudo npm install gtop -g
....
Failed to parse json
....
Failed to parse package.json data
package.json must be actual JSON, not just Javascript

This is not a bug in npm
Tell the package author to fix their package.json file. JSON.parse

One solution that works in my case is

npm cache clean

node.js prompt

How to exit

brb@brb-P45T-A:~/Downloads$ node
> Math.random()
0.14142140373587608
> .exit

HTTP server

http://www.youtube.com/watch?v=jo_B4LTHi3I

Note HTTP is just one application of TCP.

First create a js file

var http = require('http');

var s = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello \n');
  setTimeout(function() {
    res.end("world\n");
  }, 2000);
});

s.listen(8000);

Then using node program to run the js script. We can test the program by using a web browser or curl program.

# Terminal 1
node web-server.js

# Terminal 2
curl http://localhost:8000
OR use "-i" to include HTTP-header in the output
curl -i http://localhost:8000

The output I get is

$ curl -i http://localhost:8000
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Sat, 19 Oct 2013 20:55:17 GMT
Connection: keep-alive
Transfer-Encoding: chunked

Hello 
world

We can compare this with the Example from Hypertext Transfer Protocol in Wikipedia.

Test the http server

ab -n 1000 -c 100 http://localhost:8000

TCP server

Simple example

Create <tcp-server.js> file

var net= require('net')

var server = net.createServer(function(socket) {
  socket.write('hello\n');
  socket.end('world\n');
});

server.listen(8000);

After running this program, we can test it by using telnet or nc.

telnet localhost 8000
OR
nc localhost 8000

Echo server

This is modified from Simple server.

var net= require('net')

var server = net.createServer(function(socket) {
  socket.write('hello\n');
  socket.write('world\n');

  socket.on('data', function(data) {
    socket.write(data);
  });
});

server.listen(8000);

We can use netstat -an | grep tcp to lists all the TCP ports on which your Linux server is listening including all the active network connections to and from your server. This can be very helpful in determining whether slowness is due to high traffic volumes:

telnet needs to use Ctrl+] to break out the connection but nc can disconnect by using Ctrl+C.

$ telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello
world
klllkafda
klllkafda
^]

telnet> quit
Connection closed.
$
$ nc localhost 8000
hello
world


adaf
adaf
^C
$

Chat server

net = require('net');

var sockets = [];

var s = net.Server(function(socket) {
  sockets.push(socket);

  socket.on('data', function(d) {
    for(var i=0; i<sockets.length; i++) {
      if (sockets[i] == socket) continue;
      sockets[i].write(d);
    }
  });

  socket.on('end', function() {
    var i = socksets.indexOf(socket);
    sockets.splice(i, 1);
  });
});

s.listen(8000);

Test it by

Terminal 1: telnet localhost 8000

Terminal 2: telnet localhost 8000

http get

$ cat hello-world-server.js 
setInterval(function() {
  console.log("world");
 }, 2000)

console.log("hello");

var http = require('http')
setInterval(function() {
  console.log("fetching google.com");
  http.get({ host: 'google.com' }, function(res) {
    console.log(res.headers);
  });
}, 2000)

console.log("hello");