Installing node.js on FreeBSD and Using It with Nginx
I happened to stumble upon nodejs.ru, browsed through it, and added it to my feed reader. I’d wanted to try node.js for a long time, but this site was what finally tipped the scales, and I decided to try node.js in action right away.
Installation
Go to the official node.js site and copy the link to the source archive.
# cd /tmp
# fetch http://s3.amazonaws.com/four.livejournal/20100120/node-v0.1.26.tar.gz
# tar -xzvf node-v0.1.26.tar.gz
# cd node-v0.1.26
# ./configure --prefix=/usr/local
# make && make install
# rehash
If you don’t have libexecinfo installed, then:
# cd /usr/ports/devel/libexecinfo
# make install
Usage
Let’s test node itself first. To do that, create a file called example.js with the following contents:
var sys = require('sys');
sys.puts('Hello, people!');
And run that file:
# node example.js
If there are no errors, you can go ahead and hook node up to nginx. If you do get errors, post them in the comments and I’ll help.
Using It with Nginx
I’m assuming you already have Nginx installed, so I’ll go straight to the configuration for our node.js host.
If you do NOT have Nginx installed/configured, head over here.
...
location /nodejs/ {
proxy_pass http://127.0.0.1:8081/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
...
Next, let’s create a script called server.js with the following contents:
var sys = require('sys');
var http = require('http');
http.createServer(function (req, res) {
res.sendHeader(200, {'Content-Type': 'text/plain'});
res.sendBody('Hello, people!', 'utf8');
res.finish();
}).listen(8081);
sys.puts('Server running at port 8081');
Now let’s start the backend itself and restart nginx:
# node server.js
# /usr/local/etc/rc.d/nginx restart
If you start it with the –debug flag, a debugger will be available on TCP port 5858
#node --debug server.js
Go to http://localhost:8081/ and see the result!
Summary
This is an introductory article; there’s nothing complicated here, but there’s enough information to give node.js a try.
Here’s what I recommend taking a look at:
- Check out the implementation of the server-side component of a chat in node.js http://github.com/ry/node_chat/blob/master/server.js
- You can also look at the benchmarks http://four.livejournal.com/1019177.html
- And read the interesting article Nginx + Server-Side JavaScript
Comments are closed. Read the original discussion in Russian →
