├── 01_Installation └── INSTALL ├── 02_HelloWorld └── hello_world.js ├── 03_Modules ├── foobar.js └── modules.js ├── 04_Basics ├── global.js ├── process.js ├── sys.js └── timers.js ├── 05_ChildProc_FS ├── childprocess.js ├── childprocess_2.js └── filesystem.js ├── 06_dns ├── dns.js └── dns_2.js ├── 07_net ├── net_client.js └── net_server.js ├── 08_http ├── simple_client.js └── simple_server.js ├── 09_fileupload ├── multipart_old.js └── multipart_upload.js ├── 10_addons ├── dbslayer.js ├── geoip.js ├── lib │ ├── ceoip.node │ ├── dbslayer.js │ ├── geoip.js │ ├── node-ws-client.js │ └── ws.js ├── websocket_client.js └── websocket_server.js ├── 11_repl └── repl.js ├── 12_example_project ├── index.html ├── lib │ ├── ceoip.node │ ├── geoip.js │ └── ws.js └── server.js └── README /01_Installation/INSTALL: -------------------------------------------------------------------------------- 1 | INSTALL 2 | 3 | You need the following apps & addons to run the "node-by-example" code samples: 4 | 5 | Apps: 6 | - node.js: http://nodejs.org/ 7 | - MySQL: http://mysql.com/ 8 | - DBSlayer: http://code.nytimes.com/projects/dbslayer 9 | 10 | 11 | node.js Addons: 12 | - node-geoip: http://github.com/strange/node-geoip 13 | - node.ws.js: http://github.com/ncr/node.ws.js 14 | - node-ws-client.js: http://code.google.com/p/revhttp/source/browse/trunk/nodejs/node-ws-client.js 15 | - node.dbslayer.js: http://github.com/shoeman22/node.dbslayer.js 16 | 17 | 18 | Other: 19 | - Browser with WebSocket support, e.g.: Google Chrome: http://www.google.com/chrome/ 20 | - Google maps api key 21 | -------------------------------------------------------------------------------- /02_HelloWorld/hello_world.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'), 2 | http = require('http'); 3 | 4 | http.createServer(function(request, response) { 5 | setTimeout(function() { 6 | response.writeHead(200, {'Content-Type': 'text/plain'}); 7 | response.write('Hello World'); 8 | response.end(); 9 | }, 2000); 10 | }).listen(8000); 11 | sys.puts('Server running at http://127.0.0.1:8000'); 12 | -------------------------------------------------------------------------------- /03_Modules/foobar.js: -------------------------------------------------------------------------------- 1 | var foo = 'Foo'; 2 | 3 | exports.foo = function() { 4 | return foo; 5 | }; 6 | 7 | exports.bar = function(bar) { 8 | return foo + bar; 9 | }; 10 | -------------------------------------------------------------------------------- /03_Modules/modules.js: -------------------------------------------------------------------------------- 1 | var foobar = require("./foobar"), 2 | sys = require("sys"); 3 | 4 | sys.puts("Foobar: " + foobar.bar("bar")); 5 | -------------------------------------------------------------------------------- /04_Basics/global.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | some_argument = process.argv[2]; 3 | 4 | // argument example 5 | if (!some_argument) { 6 | return sys.puts("Usage: node " + __filename.replace(__dirname + "/", "") + " some_argument"); 7 | } 8 | 9 | // require example 10 | sys.puts("Default require.paths: " + require.paths); 11 | sys.puts("Adding current directory to require.paths"); 12 | require.paths.unshift(__dirname); 13 | sys.puts("Modified require.paths: " + require.paths); 14 | -------------------------------------------------------------------------------- /04_Basics/process.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"); 2 | 3 | // display all command line arguments 4 | sys.puts("Provided arguments:"); 5 | for (var key in process.argv) { 6 | sys.puts(key + ": " + process.argv[key]); 7 | } 8 | 9 | // process details (PID, platform, memory usage) 10 | sys.puts("\nPID: " + process.pid); 11 | sys.puts("Platform: " + process.platform); 12 | sys.puts("Memory usage: " + process.memoryUsage().rss); 13 | 14 | // display user environment 15 | sys.puts("\nUser Environment:"); 16 | for (var key in process.env) { 17 | sys.puts(key + ": " + process.env[key]); 18 | } 19 | 20 | // process exit code - default: success code 0 21 | process.exit(0); 22 | -------------------------------------------------------------------------------- /04_Basics/sys.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"); 2 | 3 | // sys output examples 4 | sys.puts("Output with trailing newline"); 5 | sys.print("Output without "); 6 | sys.print("new line"); 7 | sys.puts("\nAdd newline to begining and extra one at the end.\n"); 8 | sys.debug("Some debug output"); 9 | sys.log("Some log output"); 10 | 11 | // simple sys.inspect example 12 | var process_memory = process.memoryUsage(); 13 | sys.puts("\nprocess.memoryUsage():"); 14 | sys.puts(sys.inspect(process_memory)); 15 | -------------------------------------------------------------------------------- /04_Basics/timers.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"); 2 | 3 | // simple timout example - waits for 2sec before continuing with the next step 4 | var start_time = new Date(); 5 | sys.puts("Starting 2 second timer"); 6 | setTimeout(function() { 7 | var end_time = new Date(); 8 | var difference = end_time.getTime() - start_time.getTime(); 9 | sys.puts("Stopped timer after " + Math.round(difference/1000) + " seconds"); 10 | cleartimeout_example(); 11 | }, 2000); 12 | 13 | // clearTimeout example - timout set for 30secs, gets cancelled via clearTimeout right away, no output 14 | function cleartimeout_example() { 15 | var start_time = new Date(); 16 | sys.puts("\nStarting 30 second timer and stopping it immediately without triggering callback"); 17 | var timeout = setTimeout(function() { 18 | var end_time = new Date(); 19 | var difference = end_time.getTime() - start_time.getTime(); 20 | sys.puts("Stopped timer after " + Math.round(difference/1000) + " seconds"); 21 | }, 30000); 22 | clearTimeout(timeout); 23 | interval_example(); 24 | } 25 | 26 | // interval example - 5x output every 2secs using setInterval 27 | function interval_example() { 28 | var start_time = new Date(); 29 | sys.puts("\nStarting 2 second interval, stopped after 5th tick"); 30 | var count = 1; 31 | var interval = setInterval(function() { 32 | if (count == 5) clearInterval(this); 33 | var end_time = new Date(); 34 | var difference = end_time.getTime() - start_time.getTime(); 35 | sys.puts("Tick no. " + count + " after " + Math.round(difference/1000) + " seconds"); 36 | count++; 37 | }, 2000); 38 | } 39 | -------------------------------------------------------------------------------- /05_ChildProc_FS/childprocess.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | filename = process.ARGV[2]; 3 | 4 | if (!filename) 5 | return sys.puts("Usage: node " + __filename.replace(__dirname + "/", "") + " filename"); 6 | 7 | // create child process and add a listener for its "output" event 8 | var tail = require("child_process").spawn("tail", ["-f", filename]); 9 | tail.stdout.addListener("data", function(data) { 10 | sys.puts(data); 11 | }); 12 | tail.addListener("exit", function(code) { 13 | sys.puts("Child process stopped with exit code: " + code); 14 | }); 15 | 16 | // add a timer to kill the child proces after 10 seconds 17 | setTimeout(function() { 18 | tail.kill(); 19 | }, 10000); 20 | -------------------------------------------------------------------------------- /05_ChildProc_FS/childprocess_2.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | exec = require("child_process").exec; 3 | 4 | exec("ls /", function (err, stdout, stderr) { 5 | if (err) throw err; 6 | sys.puts(stdout); 7 | }); 8 | -------------------------------------------------------------------------------- /05_ChildProc_FS/filesystem.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | path = require("path"), 3 | fs = require("fs"); 4 | 5 | var file = path.join(__dirname, "test_file.txt"); 6 | 7 | fs.open(file, "w", 0644, function(err, fd) { 8 | if (err) throw err; 9 | sys.puts("File test_file.txt opened"); 10 | fs.write(fd, "Hello World", 0, "utf8", function(err, written) { 11 | sys.puts("Data written"); 12 | if (err) throw err; 13 | fs.closeSync(fd); 14 | 15 | fs.watchFile(file, function(curr, prev) { 16 | sys.puts("\n\ttest_file.txt has been edited"); 17 | sys.puts("\tThe current mtime is: " + curr.mtime); 18 | sys.puts("\tThe previous mtime was: " + prev.mtime + "\n"); 19 | }); 20 | 21 | chmod_file(); 22 | }); 23 | }); 24 | 25 | function chmod_file() { 26 | fs.chmod(file, 0777, function(err) { 27 | if (err) throw err; 28 | sys.puts("\nchmod value of test_file.txt set to 777"); 29 | 30 | fs.chmodSync(file, 0644); 31 | sys.puts("chmod value of test_file.txt set to 644"); 32 | 33 | show_dir(); 34 | }); 35 | } 36 | 37 | function show_dir() { 38 | sys.puts("\nContent of " + __dirname + ":"); 39 | fs.readdir(__dirname, function(err, files) { 40 | if (err) throw err; 41 | sys.puts(JSON.stringify(files)); 42 | show_file_content(); 43 | }); 44 | } 45 | 46 | function show_file_content() { 47 | fs.readFile(file, function(err, content) { 48 | if (err) throw err; 49 | sys.puts("\nContent of test_file.txt:"); 50 | sys.puts(content); 51 | delete_file(); 52 | }); 53 | } 54 | 55 | function delete_file() { 56 | fs.unwatchFile(file); 57 | sys.puts("\nStopping watchFile of test_file.txt"); 58 | 59 | fs.unlink(file, function(err) { 60 | if (err) throw err; 61 | sys.puts("\ntest_file.txt has been deleted."); 62 | }); 63 | } 64 | -------------------------------------------------------------------------------- /06_dns/dns.js: -------------------------------------------------------------------------------- 1 | // taken from http://nodejs.org/api.html#dns-204 2 | 3 | var sys = require("sys"), 4 | dns = require("dns"); 5 | 6 | dns.resolve4("google.com", function(err, addresses) { 7 | if (err) throw err; 8 | 9 | sys.puts("addresses: " + JSON.stringify(addresses)); 10 | 11 | for (var i = 0; i < addresses.length; i++) { 12 | var a = addresses[i]; 13 | dns.reverse(a, function (err, domains) { 14 | if (err) { 15 | sys.puts("reverse for " + a + " failed: " + err.message); 16 | } else { 17 | sys.puts("reverse for " + a + ": " + JSON.stringify(domains)); 18 | } 19 | }); 20 | } 21 | }); 22 | -------------------------------------------------------------------------------- /06_dns/dns_2.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | dns = require("dns"), 3 | domain = process.ARGV[2]; 4 | 5 | if (!domain) 6 | return sys.puts("Usage: node " + __filename.replace(__dirname + "/", "") + " domainname"); 7 | 8 | // resolve A entries 9 | dns.resolve(domain, 'A', function(err, addresses) { 10 | if (err) { 11 | if (err.errno == dns.NODATA) sys.puts("No A entry for " + domain); 12 | else throw err; 13 | } else { 14 | sys.puts("addresses: " + JSON.stringify(addresses)); 15 | } 16 | }); 17 | 18 | // resolve TXT entries 19 | dns.resolve(domain, 'TXT', function(err, addresses) { 20 | if (err) { 21 | if (err.errno == dns.NODATA) sys.puts("No TXT entry for " + domain); 22 | else throw err; 23 | } else { 24 | sys.puts("addresses: " + JSON.stringify(addresses)); 25 | } 26 | }); 27 | -------------------------------------------------------------------------------- /07_net/net_client.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | net = require("net"); 3 | 4 | var client = net.createConnection(8000); 5 | client.setEncoding("UTF8"); 6 | 7 | client.addListener("connect", function() { 8 | sys.puts("Client connected."); 9 | // close connection after 2sec 10 | setTimeout(function() { 11 | sys.puts("Sent to server: close"); 12 | client.write("close", "UTF8"); 13 | }, 2000); 14 | }); 15 | 16 | client.addListener("data", function(data) { 17 | sys.puts("Response from server: " + data); 18 | if (data == "close") client.end(); 19 | }); 20 | 21 | client.addListener("close", function(data) { 22 | sys.puts("Disconnected from server"); 23 | }); 24 | -------------------------------------------------------------------------------- /07_net/net_server.js: -------------------------------------------------------------------------------- 1 | // based on http://nodejs.org/api.html#net-server-177 2 | 3 | var sys = require("sys"), 4 | net = require("net"); 5 | 6 | var server = net.createServer(function(stream) { 7 | stream.setEncoding("utf8"); 8 | stream.addListener("connect", function() { 9 | sys.puts("Client connected"); 10 | stream.write("hello\r\n"); 11 | }); 12 | stream.addListener("data", function(data) { 13 | sys.puts("Received from client: " + data); 14 | stream.write(data); 15 | }); 16 | stream.addListener("end", function() { 17 | sys.puts("Client disconnected"); 18 | stream.write("goodbye\r\n"); 19 | stream.end(); 20 | }); 21 | }); 22 | server.listen(8000, "localhost"); 23 | 24 | // stop the server after 10 secs 25 | setTimeout(function() { 26 | server.close(); 27 | }, 10000); 28 | -------------------------------------------------------------------------------- /08_http/simple_client.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | http = require("http"); 3 | 4 | var client = http.createClient(8000, "127.0.0.1"); 5 | var request = client.request("GET", "/?query_arg=testing", {"host": "127.0.0.1"}); 6 | 7 | sys.puts("Connecting to http://127.0.0.1:8000/?query_arg=testing"); 8 | 9 | request.addListener("response", function(response) { 10 | sys.puts("STATUS: " + response.statusCode); 11 | sys.puts("HEADERS: " + JSON.stringify(response.headers)); 12 | response.setEncoding("UTF8"); 13 | response.addListener("data", function(chunk) { 14 | sys.puts("BODY: " + chunk); 15 | }); 16 | response.addListener("end", function() { 17 | sys.puts("End of response"); 18 | }); 19 | }); 20 | request.end(); 21 | -------------------------------------------------------------------------------- /08_http/simple_server.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | http = require("http"), 3 | url = require("url"), 4 | querystring = require("querystring"); 5 | 6 | http.createServer(function (request, response) { 7 | switch (url.parse(request.url).pathname) { 8 | case '/': 9 | show_index(request, response); 10 | break; 11 | default: 12 | show_404(request, response); 13 | break; 14 | } 15 | }).listen(8000); 16 | 17 | function show_index(request, response) { 18 | sys.puts("Serving index page"); 19 | response.writeHead(200, {'Content-Type': 'text/html'}); 20 | var output = 'node.js HTTP server exampleIndex output'; 21 | var url_request = url.parse(request.url).query; 22 | output += "

Request query: " + url_request + "

"; 23 | if (url_request) sys.puts("Request query: " + JSON.stringify(querystring.parse(url_request))); 24 | output += ''; 25 | response.write(output); 26 | response.end(); 27 | } 28 | 29 | function show_404(request, response) { 30 | sys.puts("Serving 404 error page"); 31 | response.writeHead(404, {'Content-Type': 'text/plain'}); 32 | response.write('404 - Please try again.'); 33 | response.end(); 34 | } 35 | -------------------------------------------------------------------------------- /09_fileupload/multipart_old.js: -------------------------------------------------------------------------------- 1 | 2 | var sys = require("sys"), 3 | events = require("events"), 4 | wrapExpression = /^[ \t]+/, 5 | multipartExpression = new RegExp( 6 | "^multipart\/(" + 7 | "mixed|rfc822|message|digest|alternative|" + 8 | "related|report|signed|encrypted|form-data|" + 9 | "x-mixed-replace|byteranges)", "i"), 10 | boundaryExpression = /boundary=([^;]+)/i, 11 | CR = "\r", 12 | LF = "\n", 13 | CRLF = CR+LF, 14 | MAX_BUFFER_LENGTH = 16 * 1024, 15 | 16 | // parser states. 17 | s = 0, 18 | S_NEW_PART = s++, 19 | S_HEADER = s++, 20 | S_BODY = s++; 21 | 22 | exports.parse = parse; 23 | exports.cat = cat; 24 | exports.Stream = Stream; 25 | 26 | // Parse a streaming message to a stream. 27 | // If the message has a "body" and no "addListener", then 28 | // just take it in and write() the body. 29 | function parse (message) { 30 | return new Stream(message); 31 | }; 32 | 33 | // WARNING: DONT EVER USE THE CAT FUNCTION IN PRODUCTION WEBSITES!! 34 | // It works pretty great, and it's a nice test function. But if 35 | // you use this function to parse an HTTP request from a live web 36 | // site, then you're essentially giving the world permission to 37 | // rack up as much memory usage as they can manage. This function 38 | // buffers the whole message, which is very convenient, but also 39 | // very much the wrong thing to do in most cases. 40 | function cat (message, callback) { 41 | var stream = parse(message); 42 | stream.files = {}; 43 | stream.fields = {}; 44 | stream.addListener("partBegin", function (part) { 45 | if (part.filename) stream.files[part.filename] = part; 46 | if (part.name) stream.fields[part.name] = part; 47 | }); 48 | stream.addListener("body", function (chunk) { 49 | stream.part.body = (stream.part.body || "") + chunk; 50 | }); 51 | stream.addListener("error", function (e) { p.emitError(e) 52 | if (callback) callback(e); 53 | }); 54 | stream.addListener("complete", function () { 55 | if (callback) callback(null, stream); 56 | }); 57 | }; 58 | 59 | // events: 60 | // "partBegin", "partEnd", "body", "complete" 61 | // everything emits on the Stream directly. 62 | // the stream's "parts" object is a nested collection of the header objects 63 | // check the stream's "part" member to know what it's currently chewin on. 64 | // this.part.parent refers to that part's containing message (which may be 65 | // the stream itself) 66 | // child messages inherit their parent's headers 67 | // A non-multipart message looks just like a multipart message with a 68 | // single part. 69 | function Stream (message) { 70 | var isMultiPart = multipartHeaders(message, this), 71 | w = isMultiPart ? writer(this) : simpleWriter(this), 72 | e = ender(this); 73 | if (message.addListener) { 74 | message.addListener("data", w); 75 | message.addListener("end", e); 76 | if (message.pause && message.resume) { 77 | this._pause = message; 78 | } 79 | } else if (message.body) { 80 | var self = this; 81 | if (message.body.pause && message.body.resume) { 82 | this._pause = message.body; 83 | } 84 | if (message.body.addListener) { 85 | message.body.addListener("data", w); 86 | message.body.addListener("end", e); 87 | } if (message.body.forEach) { 88 | var p = message.body.forEach(w); 89 | if (p && p.addCallback) p.addCallback(e); 90 | else e(); 91 | } else { 92 | // just write a string. 93 | w(message.body); 94 | e(); 95 | } 96 | } 97 | }; 98 | Stream.prototype = { 99 | __proto__ : events.EventEmitter.prototype, 100 | error : function (ex) { 101 | this._error = ex; 102 | this.emit("error", ex); 103 | }, 104 | pause : function () { 105 | if (this._pause) return this._pause.pause(); 106 | throw new Error("Unsupported"); 107 | }, 108 | resume : function () { 109 | if (this._pause) return this._pause.resume(); 110 | throw new Error("Unsupported"); 111 | } 112 | }; 113 | 114 | // check the headers of the message. If it wants to be multipart, 115 | // then we'll be returning true. Regardless, if supplied, then 116 | // stream will get a headers object that inherits from message's. 117 | // If no stream object is supplied, then this function just inspects 118 | // the message's headers for multipartness, and modifies the message 119 | // directly. This divergence is so that we can avoid modifying 120 | // the original message when we want a wrapper, but still have the 121 | // info available when it's one of our own objects. 122 | function multipartHeaders (message, stream) { 123 | var field, val, contentType, contentDisposition = ""; 124 | if (stream) stream.headers = {}; 125 | for (var h in message.headers) if (message.headers.hasOwnProperty(h)) { 126 | val = message.headers[h]; 127 | field = h.toLowerCase(); 128 | if (stream) stream.headers[field] = val; 129 | if (field === "content-type") { 130 | contentType = val; 131 | } else if (field === "content-disposition") { 132 | contentDisposition = val; 133 | } 134 | } 135 | 136 | if (!Array.isArray(contentDisposition)) { 137 | contentDisposition = contentDisposition.split(","); 138 | } 139 | contentDisposition = contentDisposition[contentDisposition.length - 1]; 140 | 141 | var mutate = (stream || message); 142 | 143 | // Name and filename can come along with either content-disposition 144 | // or content-type. Well-behaved agents use CD rather than CT, 145 | // but sadly not all agents are well-behaved. 146 | [contentDisposition, contentType].forEach(function (h) { 147 | if (!h) return; 148 | var cd = h.split(/; */); 149 | cd.shift(); 150 | for (var i = 0, l = cd.length; i < l; i ++) { 151 | var bit = cd[i].split("="), 152 | name = bit.shift(), 153 | val = stripQuotes(bit.join("=")); 154 | if (name === "filename" || name === "name") { 155 | mutate[name] = val; 156 | } 157 | } 158 | }); 159 | 160 | if (!contentType) { 161 | return false; 162 | } 163 | 164 | // legacy 165 | // TODO: Update this when/if jsgi-style headers are supported. 166 | // this will keep working, but is less efficient than it could be. 167 | if (!Array.isArray(contentType)) { 168 | contentType = contentType.split(","); 169 | } 170 | contentType = contentType[contentType.length-1]; 171 | 172 | // make sure it's actually multipart. 173 | var mpType = multipartExpression.exec(contentType); 174 | if (!mpType) { 175 | return false; 176 | } 177 | 178 | // make sure we have a boundary. 179 | var boundary = boundaryExpression.exec(contentType); 180 | if (!boundary) { 181 | return false; 182 | } 183 | 184 | mutate.type = mpType[1]; 185 | mutate.boundary = "--" + boundary[1]; 186 | mutate.isMultiPart = true; 187 | 188 | return true; 189 | }; 190 | function simpleWriter (stream) { 191 | stream.part = stream; 192 | stream.type = false; 193 | var started = false; 194 | return function (chunk) { 195 | if (!started) { 196 | stream.emit("partBegin", stream); 197 | started = true; 198 | } 199 | stream.emit("body", chunk); 200 | }; 201 | } 202 | function writer (stream) { 203 | var buffer = "", 204 | state = S_NEW_PART, 205 | part = stream.part = stream; 206 | stream.parts = []; 207 | stream.parent = stream; 208 | return function (chunk) { 209 | if (stream._error) return; 210 | // write to the buffer, and then process the buffer. 211 | buffer += chunk; 212 | while (buffer.length > 0) { 213 | while (buffer.substr(0, 2) === CRLF) buffer = buffer.substr(2); 214 | switch (state) { 215 | case S_NEW_PART: 216 | // part is a multipart message. 217 | // we're either going to start reading a new part, or we're going to 218 | // end the current part, depending on whether the boundary has -- at 219 | // the end. either way, we expect --boundary right away. 220 | var boundary = part.boundary, 221 | len = boundary.length, 222 | offset = buffer.indexOf(boundary); 223 | if (offset === -1) { 224 | if (buffer.length > MAX_BUFFER_LENGTH) { 225 | return stream.error(new Error( 226 | "Malformed: boundary not found at start of message")); 227 | } 228 | // keep waiting for it. 229 | return; 230 | } 231 | if (offset > 0) { 232 | return stream.error(Error("Malformed: data before the boundary")); 233 | } 234 | if (buffer.length < (len + 2)) { 235 | // we'll need to see either -- or CRLF after the boundary. 236 | // get it on the next pass. 237 | return; 238 | } 239 | if (buffer.substr(len, 2) === "--") { 240 | // this message is done. 241 | // chomp off the boundary and crlf and move up 242 | if (part !== stream) { 243 | // wait to see the crlf, unless this is the top-level message. 244 | if (buffer.length < (len + 4)) { 245 | return; 246 | } 247 | if (buffer.substr(len+2, 2) !== CRLF) { 248 | return stream.error(new Error( 249 | "Malformed: CRLF not found after boundary")); 250 | } 251 | } 252 | buffer = buffer.substr(len + 4); 253 | stream.emit("partEnd", part); 254 | stream.part = part = part.parent; 255 | state = S_NEW_PART; 256 | continue; 257 | } 258 | if (part !== stream) { 259 | // wait to see the crlf, unless this is the top-level message. 260 | if (buffer.length < (len + 2)) { 261 | return; 262 | } 263 | if (buffer.substr(len, 2) !== CRLF) { 264 | return stream.error(new Error( 265 | "Malformed: CRLF not found after boundary")); 266 | } 267 | } 268 | // walk past the crlf 269 | buffer = buffer.substr(len + 2); 270 | // mint a new child part, and start parsing headers. 271 | stream.part = part = startPart(part); 272 | state = S_HEADER; 273 | continue; 274 | case S_HEADER: 275 | // just grab everything to the double crlf. 276 | var headerEnd = buffer.indexOf(CRLF+CRLF); 277 | if (headerEnd === -1) { 278 | if (buffer.length > MAX_BUFFER_LENGTH) { 279 | return stream.error(new Error( 280 | "Malformed: header unreasonably long.")); 281 | } 282 | return; 283 | } 284 | var headerString = buffer.substr(0, headerEnd); 285 | // chomp off the header and the empty line. 286 | buffer = buffer.substr(headerEnd + 4); 287 | try { 288 | parseHeaderString(part.headers, headerString); 289 | } catch (ex) { 290 | return stream.error(ex); 291 | } 292 | multipartHeaders(part); 293 | 294 | // let the world know 295 | stream.emit("partBegin", part); 296 | 297 | if (part.isMultiPart) { 298 | // it has a boundary and we're ready to grab parts out. 299 | state = S_NEW_PART; 300 | } else { 301 | // it doesn't have a boundary, and is about to 302 | // start spitting out body bits. 303 | state = S_BODY; 304 | } 305 | continue; 306 | case S_BODY: 307 | // look for part.parent.boundary 308 | var boundary = part.parent.boundary, 309 | offset = buffer.indexOf(boundary); 310 | if (offset === -1) { 311 | // emit and wait for more data, but be careful, because 312 | // we might only have half of the boundary so far. 313 | // make sure to leave behind the boundary's length, so that we'll 314 | // definitely get it next time if it's on its way. 315 | var emittable = buffer.length - boundary.length; 316 | if (buffer.substr(-1) === CR) emittable -= 1; 317 | if (buffer.substr(-2) === CRLF) emittable -= 2; 318 | 319 | if (emittable > 0) { 320 | stream.emit("body", buffer.substr(0, emittable)); 321 | buffer = buffer.substr(emittable); 322 | } 323 | // haven't seen the boundary, so wait for more bytes. 324 | return; 325 | } 326 | if (offset > 0) { 327 | var emit = buffer.substr(0, offset); 328 | if (emit.substr(-2) === CRLF) emit = emit.substr(0, emit.length-2); 329 | if (emit) stream.emit("body", emit); 330 | buffer = buffer.substr(offset); 331 | } 332 | 333 | // let em know we're done. 334 | stream.emit("partEnd", part); 335 | 336 | // now buffer starts with boundary. 337 | if (buffer.substr(boundary.length, 2) === "--") { 338 | // message end. 339 | // parent ends, look for a new part in the grandparent. 340 | stream.part = part = part.parent; 341 | stream.emit("partEnd", part); 342 | stream.part = part = part.parent; 343 | state = S_NEW_PART; 344 | buffer = buffer.substr(boundary.length + 4); 345 | } else { 346 | // another part coming for the parent message. 347 | stream.part = part = part.parent; 348 | state = S_NEW_PART; 349 | } 350 | continue; 351 | } 352 | } 353 | }; 354 | }; 355 | 356 | function parseHeaderString (headers, string) { 357 | var lines = string.split(CRLF), 358 | field, value, line; 359 | for (var i = 0, l = lines.length; i < l; i ++) { 360 | line = lines[i]; 361 | if (line.match(wrapExpression)) { 362 | if (!field) { 363 | throw new Error("Malformed. First header starts with whitespace."); 364 | } 365 | value += line.replace(wrapExpression, " "); 366 | continue; 367 | } else if (field) { 368 | // now that we know it's not wrapping, put it on the headers obj. 369 | affixHeader(headers, field, value); 370 | } 371 | line = line.split(":"); 372 | field = line.shift().toLowerCase(); 373 | if (!field) { 374 | throw new Error("Malformed: improper field name."); 375 | } 376 | value = line.join(":").replace(/^\s+/, ""); 377 | } 378 | // now affix the last field. 379 | affixHeader(headers, field, value); 380 | }; 381 | 382 | function affixHeader (headers, field, value) { 383 | if (!headers.hasOwnProperty(field)) { 384 | headers[field] = value; 385 | } else if (Array.isArray(headers[field])) { 386 | headers[field].push(value); 387 | } else { 388 | headers[field] = [headers[field], value]; 389 | } 390 | }; 391 | 392 | function startPart (parent) { 393 | var part = { 394 | headers : {}, 395 | parent : parent 396 | }; 397 | parent.parts = parent.parts || []; 398 | parent.parts.push(part); 399 | return part; 400 | }; 401 | 402 | function ender (stream) { return function () { 403 | if (stream._error) return; 404 | if (!stream.isMultiPart) stream.emit("partEnd", stream); 405 | stream.emit("complete"); 406 | }}; 407 | 408 | function stripslashes(str) { 409 | // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 410 | // + improved by: Ates Goral (http://magnetiq.com) 411 | // + fixed by: Mick@el 412 | // + improved by: marrtins 413 | // + bugfixed by: Onno Marsman 414 | // + improved by: rezna 415 | // + input by: Rick Waldron 416 | // + reimplemented by: Brett Zamir (http://brett-zamir.me) 417 | // * example 1: stripslashes("Kevin\'s code"); 418 | // * returns 1: "Kevin's code" 419 | // * example 2: stripslashes("Kevin\\\'s code"); 420 | // * returns 2: "Kevin\'s code" 421 | return (str+"").replace(/\\(.?)/g, function (s, n1) { 422 | switch(n1) { 423 | case "\\": 424 | return "\\"; 425 | case "0": 426 | return "\0"; 427 | case "": 428 | return ""; 429 | default: 430 | return n1; 431 | } 432 | }); 433 | }; 434 | function stripQuotes (str) { 435 | str = stripslashes(str); 436 | return str.substr(1, str.length - 2); 437 | }; 438 | -------------------------------------------------------------------------------- /09_fileupload/multipart_upload.js: -------------------------------------------------------------------------------- 1 | // based on http://debuggable.com/posts/streaming-file-uploads-with-node-js:4ac094b2-b6c8-4a7f-bd07-28accbdd56cb 2 | 3 | var sys = require("sys"), 4 | fs = require('fs'), 5 | url = require('url'), 6 | http = require("http"), 7 | multipart = require("./multipart_old"); 8 | 9 | var name, filename, file; 10 | 11 | http.createServer(function (request, response) { 12 | switch (url.parse(request.url).pathname) { 13 | case '/': 14 | display_form(request, response); 15 | break; 16 | case '/upload': 17 | upload_file(request, response); 18 | break; 19 | default: 20 | show_404(request, response); 21 | break; 22 | } 23 | }).listen(8000); 24 | 25 | function display_form(request, response) { 26 | response.writeHead(200, {'Content-Type': 'text/html'}); 27 | response.write( 28 | '
' + 29 | '' + 30 | '' + 31 | '
' 32 | ); 33 | response.end(); 34 | } 35 | 36 | function upload_file(request, response) { 37 | request.setEncoding('binary'); 38 | 39 | var stream = new multipart.Stream(request); 40 | 41 | stream.addListener('partBegin', function(part) { 42 | // sys.debug(sys.inspect(part)); 43 | name = part.name; 44 | filename = part.filename; 45 | file = fs.createWriteStream("./upload/" + filename); 46 | }); 47 | 48 | stream.addListener('body', function(chunk) { 49 | file.write(chunk, function(err, bytesWritten) { 50 | sys.debug('bytes written: ' + bytesWritten); 51 | }); 52 | }); 53 | 54 | stream.addListener('partEnd', function(part) { 55 | file.end(); 56 | }); 57 | 58 | stream.addListener('complete', function() { 59 | return; 60 | }); 61 | 62 | response.writeHead(200, {'Content-Type': 'text/plain'}); 63 | response.write('Thanks for the upload'); 64 | response.end(); 65 | } 66 | 67 | function show_404(request, response) { 68 | response.writeHead(404, {'Content-Type': 'text/plain'}); 69 | response.write('404 - Please try again.'); 70 | response.end(); 71 | } 72 | -------------------------------------------------------------------------------- /10_addons/dbslayer.js: -------------------------------------------------------------------------------- 1 | /* This example requires the DBSlayer addon available at 2 | * http://github.com/shoeman22/node.dbslayer.js 3 | * 4 | * dbslayer -c /etc/dbslayer.conf -s lokidan -h 127.0.0.1 5 | */ 6 | 7 | /* 8 | --- 9 | name: test.js 10 | 11 | description: < 12 | This is a demonstration of how dbslayer.js can be used. 13 | It takes three parameters from the SQL query, a host 14 | 15 | author: [Guillermo Rauch](http://devthought.com) 16 | updated: [Andy Schuler](andy at leftshoedevelopment dot com) 17 | ... 18 | */ 19 | 20 | var sys = require('sys'); 21 | var dbslayer = require('./lib/dbslayer'); 22 | var sql = process.ARGV[2]; 23 | var db = new dbslayer.Server(); 24 | 25 | if (!sql){ 26 | sys.puts('Usage: node dbslayer.js sql_query'); 27 | return; 28 | } 29 | 30 | //basic query 31 | var query = db.query(sql); 32 | query.addListener("success", 33 | function(result) { 34 | sys.puts('-------------------------'); 35 | for (var i = 0, l = result.ROWS.length; i < l; i++){ 36 | sys.puts('Row ' + i + ': ' + result.ROWS[i].join(' ')); 37 | } 38 | } 39 | ); 40 | 41 | query.addListener("error", 42 | function(error, errno) { 43 | sys.puts('-------------------------'); 44 | sys.puts('MySQL error (' + (errno || '') + '): ' + error); 45 | } 46 | ); 47 | 48 | ['stat', 'client_info', 'host_info', 'server_version', 'client_version'].forEach( 49 | function(command){ 50 | var el = db[command](); 51 | el.addListener("success", 52 | function(results) { 53 | sys.puts('-------------------------'); 54 | sys.puts(command.toUpperCase() + ' ' + results); 55 | } 56 | ); 57 | 58 | el.addListener("error", 59 | function(results) { 60 | sys.puts('-------------------------'); 61 | sys.puts(command.toUpperCase() + ' ' + results); 62 | } 63 | ); 64 | } 65 | ); 66 | -------------------------------------------------------------------------------- /10_addons/geoip.js: -------------------------------------------------------------------------------- 1 | /* This example requires the GeoIP addon available at 2 | * http://github.com/strange/node-geoip 3 | */ 4 | 5 | var sys = require("sys"), 6 | geoip = require("./lib/geoip"); 7 | 8 | var dbpath = "/usr/local/share/GeoIP/GeoLiteCity.dat"; 9 | var ip = "216.236.135.152"; 10 | 11 | sys.puts("Looking up IP: " + ip); 12 | var con = new geoip.Connection(dbpath, function(con) { 13 | con.query(ip, function(result) { 14 | for (var attr in result) { 15 | sys.puts(attr + " : " + result[attr]); 16 | } 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /10_addons/lib/ceoip.node: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hendrik/node-by-example/632f7f5ebd1a02a2525f32a14289ae91823ca042/10_addons/lib/ceoip.node -------------------------------------------------------------------------------- /10_addons/lib/dbslayer.js: -------------------------------------------------------------------------------- 1 | /* 2 | --- 3 | name: dbslayer.js 4 | 5 | description: Interface to DBSlayer for Node.JS 6 | 7 | author: [Guillermo Rauch](http://devthought.com) 8 | updated: Andy Schuler (andy at leftshoedevevelopment dot com) 9 | ... 10 | */ 11 | 12 | var sys = require('sys'); 13 | var http = require('http'); 14 | var events = require('events'); 15 | 16 | var booleanCommands = ['STAT', 'CLIENT_INFO', 'HOST_INFO', 'SERVER_VERSION', 'CLIENT_VERSION']; 17 | 18 | var Server = this.Server = function(host, port, timeout){ 19 | this.host = host || 'localhost'; 20 | this.port = port || 9090; 21 | this.timeout = timeout; 22 | }; 23 | 24 | Server.prototype.fetch = function(object, key){ 25 | var e = new events.EventEmitter(); 26 | var connection = http.createClient(this.port, this.host); 27 | var request = connection.request("GET",'/db?' + escape(JSON.stringify(object)), {'host': this.host}); 28 | request.addListener('response', 29 | function(response) { 30 | var data = []; 31 | response.addListener('data', 32 | function(chunk) { 33 | data.push(chunk); 34 | } 35 | ); 36 | response.addListener('end', 37 | function() { 38 | try { 39 | var object = JSON.parse(data.join('')); 40 | } 41 | catch(err) { 42 | e.emit('error',err); 43 | return; 44 | } 45 | if (object.MYSQL_ERROR !== undefined){ 46 | e.emit('error', object.MYSQL_ERROR, object.MYSQL_ERRNO); 47 | return; 48 | } 49 | if (object.ERROR !== undefined){ 50 | e.emit('error', object.ERROR); 51 | return; 52 | } 53 | e.emit('success',key ? object[key] : object); 54 | } 55 | ); 56 | } 57 | ); 58 | request.end(); 59 | return e; 60 | } 61 | 62 | Server.prototype.query = function(query){ 63 | return this.fetch({SQL: query}, 'RESULT'); 64 | }; 65 | 66 | for (var i = 0, l = booleanCommands.length; i < l; i++){ 67 | Server.prototype[booleanCommands[i].toLowerCase()] = ( 68 | function(command){ 69 | return function(){ 70 | var obj = {}; 71 | obj[command] = true; 72 | return this.fetch(obj, command); 73 | }; 74 | } 75 | )(booleanCommands[i]); 76 | } 77 | -------------------------------------------------------------------------------- /10_addons/lib/geoip.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'), 2 | ceoip = require('./ceoip'); 3 | 4 | function Connection(dbpath, callback) { 5 | this.con = new ceoip.Connection(); 6 | this.queue = []; 7 | this.connected = false; 8 | this.currentQuery = null; 9 | this.callback = callback; 10 | 11 | var self = this; 12 | 13 | this.con.addListener('closed', function() { 14 | self.connected = false; 15 | self.emit('closed'); 16 | }); 17 | 18 | this.con.addListener('connected', function() { 19 | self.connected = true; 20 | self.callback(self); 21 | self.processQueue(); 22 | }); 23 | 24 | this.con.addListener('result', function(result) { 25 | if (self.currentQuery != null) self.currentQuery[0](result); 26 | self.currentQuery = null; 27 | self.processQueue(); 28 | }); 29 | 30 | this.con.connect(dbpath); 31 | } 32 | 33 | sys.inherits(Connection, process.EventEmitter); 34 | 35 | Connection.prototype.addJob = function(callback, ipAddress) { 36 | this.queue.push([callback, ipAddress]); 37 | this.processQueue(); 38 | }; 39 | 40 | Connection.prototype.query = function(ipAddress, callback) { 41 | this.addJob(callback, ipAddress); 42 | }; 43 | 44 | Connection.prototype.processQueue = function () { 45 | if (!this.queue.length || !this.connected || this.currentQuery) { 46 | return; 47 | } 48 | this.currentQuery = this.queue.shift(); 49 | this.con.query(this.currentQuery[1]); 50 | }; 51 | 52 | Connection.prototype.close = function () { 53 | // Emit failure on all promises in queue? 54 | this.con.close(); 55 | }; 56 | 57 | exports.Connection = Connection; 58 | -------------------------------------------------------------------------------- /10_addons/lib/node-ws-client.js: -------------------------------------------------------------------------------- 1 | /* 2 | * WebSocket NodeJS client 0.1 3 | * 4 | * Copyright 2010 Ivan Zuzak 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /* 20 | 21 | WebSocket client based on WebSocket server http://github.com/ncr/node.ws.js by Jacek Becela 22 | Example usage for testing server available at http://www.websockets.org/: 23 | 24 | var wsClient = createWSClient('ws://websockets.org:8787/'); 25 | 26 | wsClient.addListener('connect', function() { 27 | sys.puts("Connected!"); 28 | }); 29 | 30 | wsClient.addListener('data', function(chunk) { 31 | sys.puts("Received data: " + chunk); 32 | }); 33 | 34 | wsClient.addListener('close', function() { 35 | sys.puts("Disconnected!"); 36 | }); 37 | 38 | setTimeout(function() { 39 | for(var i = 0; i<10; i++) { 40 | setTimeout(function() { 41 | wsClient.write("Hello WS world! " + Math.random().toString()); 42 | }, i*200); 43 | } 44 | }, 2000); 45 | 46 | setTimeout(function() { 47 | wsClient.end(); 48 | }, 10000); 49 | 50 | */ 51 | 52 | function nano(template, data) { 53 | return template.replace(/\{([\w\.]*)}/g, function (str, key) { 54 | var keys = key.split("."), value = data[keys.shift()]; 55 | keys.forEach(function (key) { value = value[key] }); 56 | return value; 57 | }); 58 | } 59 | 60 | var sys = require("sys"); 61 | var tcp = require("net"); 62 | var url = require("url"); 63 | 64 | var handshakeTemplate = [ 65 | 'GET {path} HTTP/1.1', 66 | 'Upgrade: WebSocket', 67 | 'Connection: Upgrade', 68 | 'Host: {host}', 69 | 'Origin: {origin}', 70 | '', 71 | ''].join("\r\n"); 72 | 73 | var headerExpressions = [ 74 | /^HTTP\/1.1 101 Web Socket Protocol Handshake$/, 75 | /^Upgrade: WebSocket$/, 76 | /^Connection: Upgrade$/, 77 | /^WebSocket-Origin: (.+)$/, 78 | /^WebSocket-Location: ws:(.+)$/]; 79 | 80 | exports.createClient = function (webSocketUri, clientOrigin) { 81 | var wsUrl = webSocketUri; 82 | var wsPort = url.parse(wsUrl).port; 83 | var wsHost = url.parse(wsUrl).hostname; 84 | var wsPath = url.parse(wsUrl).pathname; 85 | var parsedWsUri = url.parse(wsUrl); 86 | parsedWsUri.port = typeof parsedWsUri.port !== 'undefined' ? parsedWsUri.port : 80; 87 | parsedWsUri.pathname = typeof parsedWsUri.pathname !== 'undefined' ? parsedWsUri.pathname : '/'; 88 | 89 | if (typeof clientOrigin === 'undefined') { 90 | clientOrigin = 'http://www.example.com'; 91 | } 92 | 93 | var socket = tcp.createConnection(wsPort, wsHost); 94 | socket.setTimeout(0); 95 | socket.setNoDelay(true); 96 | socket.setEncoding('utf8'); 97 | 98 | var emitter = new process.EventEmitter(); 99 | var handshaked = false; 100 | var buffer = ''; 101 | 102 | socket.addListener('connect', function() { 103 | var hs = nano(handshakeTemplate, { 104 | path: wsPath, 105 | host: wsHost + ":" + wsPort, 106 | origin: clientOrigin, 107 | }); 108 | socket.write(hs); 109 | }); 110 | 111 | socket.addListener('data', function (data) { 112 | if(handshaked) { 113 | handle(data); 114 | } else { 115 | handshake(data); 116 | } 117 | }); 118 | 119 | socket.addListener('end', function () { 120 | socket.end(); 121 | }); 122 | 123 | socket.addListener('close', function () { 124 | if (handshaked) { 125 | emitter.emit('close'); 126 | } 127 | }); 128 | 129 | function handshake(data) { 130 | buffer += data; 131 | if (buffer.indexOf('\r\n\r\n') < 0) { 132 | return; 133 | } 134 | var headers = buffer.split('\r\n'); 135 | 136 | var matches = [], match; 137 | for (var i = 0, l = headerExpressions.length; i < l; i++) { 138 | match = headerExpressions[i].exec(headers[i]); 139 | 140 | if (match) { 141 | if(match.length > 1) { 142 | matches.push(match[1]); 143 | } 144 | } else { 145 | socket.end(); 146 | return; 147 | } 148 | } 149 | 150 | handshaked = true; 151 | emitter.emit('connect'); 152 | buffer = ''; 153 | } 154 | 155 | function handle(data) { 156 | buffer += data; 157 | 158 | var chunks = buffer.split('\uffff'); 159 | var count = chunks.length - 1; // last is "" or a partial packet 160 | 161 | for(var i = 0; i < count; i++) { 162 | var chunk = chunks[i]; 163 | if(chunk[0] == '\u0000') { 164 | emitter.emit('data', chunk.slice(1)); 165 | } else { 166 | socket.end(); 167 | return; 168 | } 169 | } 170 | 171 | buffer = chunks[count]; 172 | } 173 | 174 | emitter.remoteAddress = socket.remoteAddress; 175 | 176 | emitter.write = function (data) { 177 | try { 178 | // socket.write('\u0000' + data + '\uffff'); 179 | socket.write('\u0000', 'binary'); 180 | socket.write(data, 'utf8'); 181 | socket.write('\uffff', 'binary'); 182 | } catch(e) { 183 | socket.end(); 184 | } 185 | } 186 | 187 | emitter.close = function () { 188 | socket.end(); 189 | } 190 | 191 | return emitter; 192 | } 193 | -------------------------------------------------------------------------------- /10_addons/lib/ws.js: -------------------------------------------------------------------------------- 1 | // Github: http://github.com/ncr/node.ws.js 2 | // Compatible with node v0.1.91 3 | // Author: Jacek Becela 4 | // License: MIT 5 | // Based on: http://github.com/Guille/node.websocket.js 6 | 7 | function nano(template, data) { 8 | return template.replace(/\{([\w\.]*)}/g, function (str, key) { 9 | var keys = key.split("."), value = data[keys.shift()]; 10 | keys.forEach(function (key) { value = value[key] }); 11 | return value; 12 | }); 13 | } 14 | 15 | var sys = require("sys"), 16 | net = require("net"), 17 | headerExpressions = [ 18 | /^GET (\/[^\s]*) HTTP\/1\.1$/, 19 | /^Upgrade: WebSocket$/, 20 | /^Connection: Upgrade$/, 21 | /^Host: (.+)$/, 22 | /^Origin: (.+)$/ 23 | ], 24 | handshakeTemplate = [ 25 | 'HTTP/1.1 101 Web Socket Protocol Handshake', 26 | 'Upgrade: WebSocket', 27 | 'Connection: Upgrade', 28 | 'WebSocket-Origin: {origin}', 29 | 'WebSocket-Location: ws://{host}{resource}', 30 | '', 31 | '' 32 | ].join("\r\n"), 33 | policy_file = ''; 34 | 35 | exports.createServer = function (websocketListener) { 36 | return net.createServer(function (socket) { 37 | socket.setTimeout(0); 38 | socket.setNoDelay(true); 39 | socket.setEncoding("utf8"); 40 | 41 | var emitter = new process.EventEmitter(), 42 | handshaked = false, 43 | buffer = ""; 44 | 45 | function handle(data) { 46 | buffer += data; 47 | 48 | var chunks = buffer.split("\ufffd"), 49 | count = chunks.length - 1; // last is "" or a partial packet 50 | 51 | for(var i = 0; i < count; i++) { 52 | var chunk = chunks[i]; 53 | if(chunk[0] == "\u0000") { 54 | emitter.emit("data", chunk.slice(1)); 55 | } else { 56 | socket.end(); 57 | return; 58 | } 59 | } 60 | 61 | buffer = chunks[count]; 62 | } 63 | 64 | function handshake(data) { 65 | var headers = data.split("\r\n"); 66 | 67 | if(//.exec(headers[0])) { 68 | socket.write(policy_file); 69 | socket.end(); 70 | return; 71 | } 72 | 73 | var matches = [], match; 74 | for (var i = 0, l = headerExpressions.length; i < l; i++) { 75 | match = headerExpressions[i].exec(headers[i]); 76 | 77 | if (match) { 78 | if(match.length > 1) { 79 | matches.push(match[1]); 80 | } 81 | } else { 82 | socket.end(); 83 | return; 84 | } 85 | } 86 | 87 | socket.write(nano(handshakeTemplate, { 88 | resource: matches[0], 89 | host: matches[1], 90 | origin: matches[2], 91 | })); 92 | 93 | handshaked = true; 94 | emitter.emit("connect", matches[0]); 95 | } 96 | 97 | socket.addListener("data", function (data) { 98 | if(handshaked) { 99 | handle(data); 100 | } else { 101 | handshake(data); 102 | } 103 | }).addListener("end", function () { 104 | socket.end(); 105 | }).addListener("close", function () { 106 | if (handshaked) { // don't emit close from policy-requests 107 | emitter.emit("close"); 108 | } 109 | }); 110 | 111 | emitter.remoteAddress = socket.remoteAddress; 112 | 113 | emitter.write = function (data) { 114 | try { 115 | socket.write('\u0000', 'binary'); 116 | socket.write(data, 'utf8'); 117 | socket.write('\uffff', 'binary'); 118 | } catch(e) { 119 | // Socket not open for writing, 120 | // should get "close" event just before. 121 | socket.end(); 122 | } 123 | } 124 | 125 | emitter.end = function () { 126 | socket.end(); 127 | } 128 | 129 | websocketListener(emitter); // emits: "connect", "data", "close", provides: write(data), end() 130 | }); 131 | } 132 | -------------------------------------------------------------------------------- /10_addons/websocket_client.js: -------------------------------------------------------------------------------- 1 | /* This example requires the websocket client addon available at 2 | * http://code.google.com/p/revhttp/source/browse/trunk/nodejs/node-ws-client.js 3 | */ 4 | 5 | var sys = require("sys"), 6 | ws = require("./lib/node-ws-client"); 7 | 8 | var wsClient = ws.createClient('ws://127.0.0.1:8000/'); 9 | 10 | wsClient.addListener('connect', function() { 11 | sys.puts("Connected!"); 12 | wsClient.write("Testing"); 13 | }); 14 | 15 | wsClient.addListener('data', function(chunk) { 16 | sys.puts("Received data: " + chunk); 17 | }); 18 | 19 | wsClient.addListener('close', function() { 20 | sys.puts("Disconnected!"); 21 | }); 22 | 23 | setTimeout(function() { 24 | for(var i = 0; i<10; i++) { 25 | setTimeout(function() { 26 | wsClient.write("Hello WS world! " + Math.random().toString()); 27 | sys.debug('data sent'); 28 | }, i*200); 29 | } 30 | }, 2000); 31 | 32 | setTimeout(function() { 33 | wsClient.close(); 34 | }, 10000); 35 | -------------------------------------------------------------------------------- /10_addons/websocket_server.js: -------------------------------------------------------------------------------- 1 | /* This example requires the websocket addon available at 2 | * http://github.com/ncr/node.ws.js 3 | */ 4 | 5 | var sys = require("sys"), 6 | ws = require("./lib/ws"); 7 | 8 | ws.createServer(function (websocket) { 9 | websocket.addListener("connect", function (resource) { 10 | sys.debug("connect: " + resource); 11 | websocket.write("test"); 12 | setTimeout(websocket.end, 10 * 1000); 13 | }); 14 | websocket.addListener("data", function (data) { 15 | sys.debug('DATA: ' + data); 16 | websocket.write("Thanks!"); 17 | }); 18 | websocket.addListener("close", function () { 19 | sys.debug("close"); 20 | }); 21 | }).listen(8000); 22 | -------------------------------------------------------------------------------- /11_repl/repl.js: -------------------------------------------------------------------------------- 1 | var sys = require("sys"), 2 | net = require("net"), 3 | repl = require("repl"); 4 | 5 | no_connections = 0; 6 | some_var = "Hello"; 7 | net.createServer(function(socket) { 8 | sys.puts("Connection!"); 9 | no_connections += 1; 10 | socket.end(); 11 | }).listen(8000); 12 | 13 | repl.start("repl.js prompt> "); 14 | 15 | -------------------------------------------------------------------------------- /12_example_project/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Node by example: Chapter 12 5 | 6 | 7 | 8 | 9 | 13 | 14 | 15 |
16 | 17 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /12_example_project/lib/ceoip.node: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hendrik/node-by-example/632f7f5ebd1a02a2525f32a14289ae91823ca042/12_example_project/lib/ceoip.node -------------------------------------------------------------------------------- /12_example_project/lib/geoip.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'), 2 | ceoip = require('./ceoip'); 3 | 4 | function Connection(dbpath, callback) { 5 | this.con = new ceoip.Connection(); 6 | this.queue = []; 7 | this.connected = false; 8 | this.currentQuery = null; 9 | this.callback = callback; 10 | 11 | var self = this; 12 | 13 | this.con.addListener('closed', function() { 14 | self.connected = false; 15 | self.emit('closed'); 16 | }); 17 | 18 | this.con.addListener('connected', function() { 19 | self.connected = true; 20 | self.callback(self); 21 | self.processQueue(); 22 | }); 23 | 24 | this.con.addListener('result', function(result) { 25 | if (self.currentQuery != null) self.currentQuery[0](result); 26 | self.currentQuery = null; 27 | self.processQueue(); 28 | }); 29 | 30 | this.con.connect(dbpath); 31 | } 32 | 33 | sys.inherits(Connection, process.EventEmitter); 34 | 35 | Connection.prototype.addJob = function(callback, ipAddress) { 36 | this.queue.push([callback, ipAddress]); 37 | this.processQueue(); 38 | }; 39 | 40 | Connection.prototype.query = function(ipAddress, callback) { 41 | this.addJob(callback, ipAddress); 42 | }; 43 | 44 | Connection.prototype.processQueue = function () { 45 | if (!this.queue.length || !this.connected || this.currentQuery) { 46 | return; 47 | } 48 | this.currentQuery = this.queue.shift(); 49 | this.con.query(this.currentQuery[1]); 50 | }; 51 | 52 | Connection.prototype.close = function () { 53 | // Emit failure on all promises in queue? 54 | this.con.close(); 55 | }; 56 | 57 | exports.Connection = Connection; 58 | -------------------------------------------------------------------------------- /12_example_project/lib/ws.js: -------------------------------------------------------------------------------- 1 | // Github: http://github.com/ncr/node.ws.js 2 | // Compatible with node v0.1.91 3 | // Author: Jacek Becela 4 | // License: MIT 5 | // Based on: http://github.com/Guille/node.websocket.js 6 | 7 | function nano(template, data) { 8 | return template.replace(/\{([\w\.]*)}/g, function (str, key) { 9 | var keys = key.split("."), value = data[keys.shift()]; 10 | keys.forEach(function (key) { value = value[key] }); 11 | return value; 12 | }); 13 | } 14 | 15 | var sys = require("sys"), 16 | net = require("net"), 17 | headerExpressions = [ 18 | /^GET (\/[^\s]*) HTTP\/1\.1$/, 19 | /^Upgrade: WebSocket$/, 20 | /^Connection: Upgrade$/, 21 | /^Host: (.+)$/, 22 | /^Origin: (.+)$/ 23 | ], 24 | handshakeTemplate = [ 25 | 'HTTP/1.1 101 Web Socket Protocol Handshake', 26 | 'Upgrade: WebSocket', 27 | 'Connection: Upgrade', 28 | 'WebSocket-Origin: {origin}', 29 | 'WebSocket-Location: ws://{host}{resource}', 30 | '', 31 | '' 32 | ].join("\r\n"), 33 | policy_file = ''; 34 | 35 | exports.createServer = function (websocketListener) { 36 | return net.createServer(function (socket) { 37 | socket.setTimeout(0); 38 | socket.setNoDelay(true); 39 | socket.setEncoding("utf8"); 40 | 41 | var emitter = new process.EventEmitter(), 42 | handshaked = false, 43 | buffer = ""; 44 | 45 | function handle(data) { 46 | buffer += data; 47 | 48 | var chunks = buffer.split("\ufffd"), 49 | count = chunks.length - 1; // last is "" or a partial packet 50 | 51 | for(var i = 0; i < count; i++) { 52 | var chunk = chunks[i]; 53 | if(chunk[0] == "\u0000") { 54 | emitter.emit("data", chunk.slice(1)); 55 | } else { 56 | socket.end(); 57 | return; 58 | } 59 | } 60 | 61 | buffer = chunks[count]; 62 | } 63 | 64 | function handshake(data) { 65 | var headers = data.split("\r\n"); 66 | 67 | if(//.exec(headers[0])) { 68 | socket.write(policy_file); 69 | socket.end(); 70 | return; 71 | } 72 | 73 | var matches = [], match; 74 | for (var i = 0, l = headerExpressions.length; i < l; i++) { 75 | match = headerExpressions[i].exec(headers[i]); 76 | 77 | if (match) { 78 | if(match.length > 1) { 79 | matches.push(match[1]); 80 | } 81 | } else { 82 | socket.end(); 83 | return; 84 | } 85 | } 86 | 87 | socket.write(nano(handshakeTemplate, { 88 | resource: matches[0], 89 | host: matches[1], 90 | origin: matches[2], 91 | })); 92 | 93 | handshaked = true; 94 | emitter.emit("connect", matches[0]); 95 | } 96 | 97 | socket.addListener("data", function (data) { 98 | if(handshaked) { 99 | handle(data); 100 | } else { 101 | handshake(data); 102 | } 103 | }).addListener("end", function () { 104 | socket.end(); 105 | }).addListener("close", function () { 106 | if (handshaked) { // don't emit close from policy-requests 107 | emitter.emit("close"); 108 | } 109 | }); 110 | 111 | emitter.remoteAddress = socket.remoteAddress; 112 | 113 | emitter.write = function (data) { 114 | try { 115 | socket.write('\u0000', 'binary'); 116 | socket.write(data, 'utf8'); 117 | socket.write('\uffff', 'binary'); 118 | } catch(e) { 119 | // Socket not open for writing, 120 | // should get "close" event just before. 121 | socket.end(); 122 | } 123 | } 124 | 125 | emitter.end = function () { 126 | socket.end(); 127 | } 128 | 129 | websocketListener(emitter); // emits: "connect", "data", "close", provides: write(data), end() 130 | }); 131 | } 132 | -------------------------------------------------------------------------------- /12_example_project/server.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'), 2 | ws = require('./lib/ws'); 3 | geoip = require('./lib/geoip'), 4 | dbpath = '/usr/local/share/GeoIP/GeoLiteCity.dat', 5 | ip_cache = [], 6 | filename = process.ARGV[2]; 7 | 8 | if (!filename) 9 | return sys.puts('Usage: node ' + __filename + ' filename'); 10 | 11 | function result_output(result, websocket) { 12 | var json_result = {}; 13 | for (var key in result) json_result[key] = result[key]; 14 | websocket.write(JSON.stringify(json_result)); 15 | } 16 | 17 | function db_connect(ip, websocket) { 18 | var con = new geoip.Connection(dbpath, function(con) { 19 | con.query(ip, function(result) { 20 | result_output(result, websocket); 21 | con.close(); 22 | }); 23 | }); 24 | } 25 | 26 | var tail = require('child_process').spawn('tail', ['-f', filename]); 27 | sys.debug('start tailing logfile'); 28 | 29 | ws.createServer(function(websocket) { 30 | websocket.addListener('connect', function(response) { 31 | sys.debug('connect: ' + response); 32 | 33 | tail.stdout.addListener('data', function(data) { 34 | ip = data.toString().split(" ")[0]; 35 | if (!ip_cache[ip]) { 36 | sys.debug(ip); 37 | ip_cache[ip] = true; 38 | db_connect(ip, websocket); 39 | } 40 | }); 41 | 42 | }).addListener('data', function(data) { 43 | sys.debug(data); 44 | }).addListener('close', function() { 45 | sys.debug('close'); 46 | }); 47 | }).listen(8000); 48 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | node.js by example - simple code examples of the available features of node.js 2 | These are the code examples for the Node By Example series available at: 3 | http://blog.osbutler.com/tags/node-by-example/ 4 | 5 | Compatibile with node v0.2.0 6 | 7 | For questions & comments go to http://blog.osbutler.com/ 8 | --------------------------------------------------------------------------------