node.js cheatsheet
Some of this I got from Node: Up and Running by Tom Hughes-
Croucher and Mike Wilson (O'Reilly). Copyright 2012 Tom Hughes-Croucher and
Mike Wilson, 978-1-449-39858-3.
Table of Contents
...
installing locally
https://www.digitalocean.com/community/articles/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04
sudo apt-get update
sudo apt-get install build-essential
sudo apt-get install curl
echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
. ~/.bashrc
mkdir ~/local
mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install
curl -L https://npmjs.org/install.sh | sh
node -v
#install android environment for cordova
http://developer.android.com/sdk/installing/index.html
download eclipse ADT
save to Development directory
download latest version, gunzip, untar
./configure --prefix=~/nodejs (or other dir for install)
make (?)
make install
curl https://npmjs.org/install.sh | sh (installs npm)
what version of node.js am I running
http://nodejs.org/docs/v0.10.12/api/process.html#process_process_version
node
> console.log('Version: ' + process.version);prout object properties
http://nodejs.org/api/util.html#util_util_inspect_object_options
var util = require('util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
Events
var utils = require('utils');
EventEmitter = require('events').EventEmitter;
var Server = function() {
  console.log('init');
};
util.inherits(Server, EventEmitter);
var s = new Server();
s.on('xyz', function() {
    console.log('xyz');
});
s.emit('xyz');
passing params when emitting an event
s.emit('xyz', param1, param2, param3);
http server
var http = require('http');
var server = http.createServer();
var handleReq = function(req,res){
  res.writeHead(200, {});
  res.end('uh hello');
};
server.on('request', handleReq);
server.listen(8000);
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
    }).listen(8124, "127.0.0.1");events
- request - http request
- connection - 1 connection event for for multiple http events
- checkContinue - event handler for this will cause request not to be emitted - client streams chunks of data to server, and sends events along the way
- upgrade - client asks for protocol upgrade - http server will deny unless event handler exist
- clientError - error event sent by client
http client
get
var http = require('http');
var opts = {
    host: 'www.website.com',
    port: 80,
    path: '/',
    method: 'GET'
};
var req = http.request(opts, function(res) {
    console.log(res);
    res.on('data', function(data) {
        console.log(data);
    });
});
/* need to end or request won't initiate the http req
req.end();
***OR***
var http = require('http');
var opts = {
  host: 'www.website.com',
  port: 80,
  path: '/',
};
var req = http.get(opts, function(res) {
  console.log(res);
  /* instead of seeing data in hex, see it in utf8 */
  res.setEncoding('utf8');
  res.on('data', function(data) {
    console.log(data);
  });
});put
var options = {
host: 'www.website.com',
      port: 80,
      path: '/submit',
      method: 'POST'
};
var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
      });
    });
req.write("Da Data");
req.write("Da Data2");
req.end();clientResponse
- statusCode - http status
- header - response header
URL module
> var daURL = "http://website.net/some/url/?with=query¶m=that#dahash";
undefined
> parsedURL = URL.parse(daURL);
{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'website.net',
  port: null,
  hostname: 'website.net',
  hash: '#dahash',
  search: '?with=query¶m=that',
  query: 'with=query¶m=that',
  pathname: '/some/url/',
  path: '/some/url/?with=query¶m=that',
  href: 'http://website.net/some/url/?with=query¶m=that#dahash' }
> parsedURL = URL.parse(daURL, true);
{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'website.net',
  port: null,
  hostname: 'website.net',
  hash: '#dahash',
  search: '?with=query¶m=that',
  query: { with: 'query', param: 'that' },
  pathname: '/some/url/',
  path: '/some/url/?with=query¶m=that',
  href: 'http://website.net/some/url/?with=query¶m=that#dahash' } stdin with URL module
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
    process.stdout.write('data: ' + chunk);
    data=chunk.toString('utf-8').trim();
    console.log("data as string: ", data);
    if (data == "quit") {
      process.stdout.write('bye');
      process.exit(0);
      }
    });
/* this doesn' seem to be called */
process.stdin.on('end', function () {
    process.stdout.write('end');
    });
***OR***
/* Run this from a file - messes up when manually entered */
var URL = require('url')
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdout.write('enter url: ');
process.stdin.on('data', function (chunk) {
    daURL=chunk.toString('utf-8').trim();
    console.log("data as string: ", daURL);
    if (daURL == "quit") {
      process.stdout.write('bye');
      process.exit(0);
      }
    parsedURL = URL.parse(daURL,true);
    console.log(parsedURL);
/* for some reason this was not working for parsedURL   
    process.stdout.write(parsedURL); */
    process.stdout.write('enter url (or quit): ');
    });
querystring
var querystring = require('querystring');
querystring.parse('blah=1&dah=2&sha=3');
{ blah: '1', dah: '2', sha: '3' }
var daObject = {'whel':1, 'I':22, 'never':'knew'};
querystring.encode(daObject);
readable streams
var fs=require('fs');
var filehandle = fs.readFile('../../../delme.txt', function(err, data) {
    console.log('chunk');
    console.log(data);
});
*** spooling - wait for end of stream ***
var spool = "";
stream.on('data', function(data) {
  daspool += data;
});
stream.on('end', function() {
  console.log(daspool);
});
Filesystem
fs.readFile('dafile.txt', function(e, data) {
  /* when readFile returns prout dafile */
  console.log('dafile: ' + data);
  /* after prout - delete dafile */
  fs.unlink('dafile.txt');
});
Buffers
- extension to V8 engine
- direct allocation of memory (storage)
- fixed size
- common to use buffers for string storage, as it's quicker to move them around that JavaScript strings
/* create a buffer with 3 bytes */
new Buffer([254,1,149]);
<Buffer fe 01 95>
/* uninitialized buffer with 3 bytes */
new Buffer(3);
<Buffer ff 01 95>
new Buffer('blah');
<Buffer 62 6c 61 68>
new Buffer('é', 'utf8');
<Buffer c3 a9>
new Buffer('é', 'ascii');
<Buffer e9>
strings with buffers
- new Buffer('téxt') will figure the write length for the buffer
- Buffer.byteLength() will measure byte length of string
- Buffer.write() writes string to specific index of Buffer.  If room, ntire string will be written.  Otherwise truncated.  ALSO used to terminate the string with a null
var daBuffer = new Buffer(7);
> daBuffer.write('zzzzzzz')
7
> daBuffer
<Buffer 7a 7a 7a 7a 7a 7a 7a>
> daBuffer.write('mn',2);
2
> daBuffer
<Buffer 7a 7a 6d 6e 7a 7a 7a>
Helpers
DNS
dns.resolve('domain.com', 'dnstype', callbackfunction());
- dnstype can be A, CNAME, MX, TXT, SRV, etc
var dns = require('dns');
dns.resolve('domain.com', 'A', function(success, rest) {
    if (success) {
      console.log(success);
      }
    console.log(rest);
});
crypto
hashes
var crypto = require('crypto');
var md5 = crypto.createHash('md5'); /* MD5, SHA1, RIPEMD, SHA256, SHA512 */
md5.update('blah');
md5.digest('hex'); /* no more data after hash.digest(); */
                   /* binary, hex, base64 */
'abcd23456...'
var sha1 = crypto.createHash('sha1');
sha1.update('foo');
sha1.update('bar');
sha1.digest('hex');
HMAC
hash of object and password
(at CLI)
openssl genrsa -out key.pem 1024
(run node)
var crypto = require('crypto');
var filehandle = require('fs');
var pem = filehandle.readFileSync('key.pem');
var key = pem.toString('ascii');
var hmac = crypto.createHmac('sha256',key);
hmac.update('blahblah');
hmac.digest('hex');
Public/Private Key
openssl req -key key.pem -new -x509 -out cert.pem
(extract public key from private key generated above)
Cipher
encrypt data using private key
supports algorthms that coe compiled into OpenSSL.  (e.g.
Decipher
var crypto = require('crypto');
var filehandle = require('fs');
var pem = filehandle.readFileSync('key.pem');
var key = pem.toString('ascii');
var plaintext = new Buffer ('blahblahblah');
var encrypted = ""
var cipher = crypto.createCipher('blowfish',key);
encrypted += cipher.update(plaintext, 'binary', 'hex');
encrypted += cipher.final('hex');
var decrypted = "";
var decipher = crypto.createDecipher('blowfish', key);
decrypted += decipher.update(encrypted, 'hex', 'binary');
decrypted += decipher.final('binary');
var output = new Buffer(decrypted);
output
plaintext