Skip to content

Instantly share code, notes, and snippets.

@heliostatic
Forked from bergie/README.md
Created May 19, 2011 16:03
Show Gist options
  • Save heliostatic/981123 to your computer and use it in GitHub Desktop.
Save heliostatic/981123 to your computer and use it in GitHub Desktop.

Revisions

  1. @bergie bergie revised this gist May 19, 2011. 1 changed file with 20 additions and 1 deletion.
    21 changes: 20 additions & 1 deletion README.md
    Original file line number Diff line number Diff line change
    @@ -1 +1,20 @@
    Some exercises from the [Falsy Values](http://falsyvalues.com/) workshops. [Liveblogs](http://www.qaiku.com/go/blzq/).
    Some exercises from the [Falsy Values](http://falsyvalues.com/) workshops.

    The good parts:

    * HTTP server and client in [same script](#file_clientserver.coffee)
    * Express [cookies example](#file_express.coffee)
    * Express [routing example](#file_express_routing.coffee)
    * Express [error handling](#file_express_error.coffee)
    * Express [middlewares example](#file_express_middlewares.coffee)
    * Simple [HTTP proxy](#file_proxy.coffee)
    * [Blog example](#file_blog.coffee) using views, middlewares and routing
    * CommonJS [module](#file_fish.coffee) and [script using it](#file_use_fish.coffee)
    * [async.auto example](#file_asynchttppost.coffee)
    * [async.parallel example](#file_asyncwebfetch.coffee)
    * Chat server with web and TCP front-ends: [client](#file_images%2Fsocket.coffee) and [server](#file_sockets.coffee)

    Read more:

    * [Liveblogs](http://www.qaiku.com/go/blzq/)
    * [HN thread](http://news.ycombinator.com/item?id=2563642)
  2. @bergie bergie revised this gist May 19, 2011. 2 changed files with 15 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions cluster.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    cluster = require "cluster"

    app = require("./clusterWorker").server

    workers = cluster app
    workers.use cluster.debug()
    workers.listen 8003
    8 changes: 8 additions & 0 deletions clusterWorker.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    express = require "express"

    app = express.createServer()

    app.get "/hello/:name", (req, res, next) ->
    res.send "Hello, #{req.params.name}"

    exports.server = app
  3. @bergie bergie revised this gist May 19, 2011. 1 changed file with 29 additions and 4 deletions.
    33 changes: 29 additions & 4 deletions sockets.coffee
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    express = require "express"
    io = require "socket.io"
    net = require "net"

    app = express.createServer()

    @@ -13,13 +14,37 @@ app.get "/", (req, res, next) ->

    app.listen 8003



    forwardMessage = (msg, sender) ->
    # Forward to web chat users
    for clientId, clientObject of socket.clients
    if clientObject isnt sender
    clientObject.send msg

    for client in tcpClients
    if client isnt sender
    client.write "#{msg}\n"

    socket = io.listen app
    socket.on "connection", (client) ->
    client.send "Hi there"
    client.on "message", (msg) ->
    console.log "Got message", msg
    for clientId, clientObject of socket.clients
    if clientObject isnt client
    clientObject.send msg
    forwardMessage msg, client
    client.on "disconnect", ->
    console.log "Client disconnected"
    console.log "Client disconnected"

    tcpClients = []
    tcp = net.createServer (client) ->
    client.setEncoding "utf-8"
    client.on "connect", ->
    tcpClients.push client
    console.log "Connection from #{socket.remoteAddress}"
    client.write "Hi, there\n"

    client.on "data", (msg) ->
    console.log "Got #{msg}"
    forwardMessage msg, client

    tcp.listen 3000, "localhost"
  4. @bergie bergie revised this gist May 19, 2011. 3 changed files with 27 additions and 10 deletions.
    4 changes: 4 additions & 0 deletions images/simple.css
    Original file line number Diff line number Diff line change
    @@ -8,4 +8,8 @@ body {

    h1 a {
    color: black;
    }

    li.own {
    color: #c0c0c0;
    }
    14 changes: 10 additions & 4 deletions images/socket.coffee
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,15 @@
    addItem = (msg, own) ->
    newItem = jQuery "<li>#{msg}</li>"
    if own
    newItem.attr "class", "own"
    jQuery("ul").append newItem

    socket = new io.Socket()
    socket.connect()
    socket.on "connect", ->
    socket.send "Hello there"
    jQuery("#input").attr "disabled", false
    socket.on "message", (msg) ->
    newItem = jQuery "<li>#{msg}</li>"
    jQuery("ul").append newItem
    addItem msg
    socket.on "disconnect", ->
    jQuery("#input").attr "disabled", true
    socket.connect()
    @@ -14,4 +18,6 @@ jQuery(document).ready ->
    console.log "Binding", jQuery("#send")
    jQuery("#send").bind "click", ->
    console.log "Send clicked"
    socket.send jQuery("#input").val()
    addItem jQuery("#input").val(), true
    socket.send jQuery("#input").val()
    jQuery("#input").val ""
    19 changes: 13 additions & 6 deletions images/socket.js
    Original file line number Diff line number Diff line change
    @@ -1,15 +1,20 @@
    (function() {
    var socket;
    var addItem, socket;
    addItem = function(msg, own) {
    var newItem;
    newItem = jQuery("<li>" + msg + "</li>");
    if (own) {
    newItem.attr("class", "own");
    }
    return jQuery("ul").append(newItem);
    };
    socket = new io.Socket();
    socket.connect();
    socket.on("connect", function() {
    socket.send("Hello there");
    return jQuery("#input").attr("disabled", false);
    });
    socket.on("message", function(msg) {
    var newItem;
    newItem = jQuery("<li>" + msg + "</li>");
    return jQuery("ul").append(newItem);
    return addItem(msg);
    });
    socket.on("disconnect", function() {
    jQuery("#input").attr("disabled", true);
    @@ -19,7 +24,9 @@
    console.log("Binding", jQuery("#send"));
    return jQuery("#send").bind("click", function() {
    console.log("Send clicked");
    return socket.send(jQuery("#input").val());
    addItem(jQuery("#input").val(), true);
    socket.send(jQuery("#input").val());
    return jQuery("#input").val("");
    });
    });
    }).call(this);
  5. @bergie bergie revised this gist May 19, 2011. 4 changed files with 80 additions and 0 deletions.
    17 changes: 17 additions & 0 deletions images/socket.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    socket = new io.Socket()
    socket.connect()
    socket.on "connect", ->
    socket.send "Hello there"
    jQuery("#input").attr "disabled", false
    socket.on "message", (msg) ->
    newItem = jQuery "<li>#{msg}</li>"
    jQuery("ul").append newItem
    socket.on "disconnect", ->
    jQuery("#input").attr "disabled", true
    socket.connect()

    jQuery(document).ready ->
    console.log "Binding", jQuery("#send")
    jQuery("#send").bind "click", ->
    console.log "Send clicked"
    socket.send jQuery("#input").val()
    25 changes: 25 additions & 0 deletions images/socket.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    (function() {
    var socket;
    socket = new io.Socket();
    socket.connect();
    socket.on("connect", function() {
    socket.send("Hello there");
    return jQuery("#input").attr("disabled", false);
    });
    socket.on("message", function(msg) {
    var newItem;
    newItem = jQuery("<li>" + msg + "</li>");
    return jQuery("ul").append(newItem);
    });
    socket.on("disconnect", function() {
    jQuery("#input").attr("disabled", true);
    return socket.connect();
    });
    jQuery(document).ready(function() {
    console.log("Binding", jQuery("#send"));
    return jQuery("#send").bind("click", function() {
    console.log("Send clicked");
    return socket.send(jQuery("#input").val());
    });
    });
    }).call(this);
    25 changes: 25 additions & 0 deletions sockets.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    express = require "express"
    io = require "socket.io"

    app = express.createServer()

    app.use "/images", express.static "#{process.cwd()}/images"
    app.set "view engine", "jade"
    app.set "view options",
    layout: false

    app.get "/", (req, res, next) ->
    res.render "chat"

    app.listen 8003

    socket = io.listen app
    socket.on "connection", (client) ->
    client.send "Hi there"
    client.on "message", (msg) ->
    console.log "Got message", msg
    for clientId, clientObject of socket.clients
    if clientObject isnt client
    clientObject.send msg
    client.on "disconnect", ->
    console.log "Client disconnected"
    13 changes: 13 additions & 0 deletions views/chat.jade
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    html
    head
    title My blog
    link(rel="stylesheet", href="/images/simple.css")
    script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js")
    script(src="/socket.io/socket.io.js")
    script(src="/images/socket.js")
    body
    ul(class="messages")
    div
    input(type="text", id="input")
    button(id="send") Send

  6. @bergie bergie revised this gist May 19, 2011. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions expressRouting.coffee
    Original file line number Diff line number Diff line change
    @@ -23,8 +23,7 @@ app.all "/products/*", (req, res, next) ->
    next()

    app.get "/products", (req, res) ->
    res.write "Our cool products"
    res.end()
    res.end "Our cool products"

    findProduct = (id) ->
    if id isnt "abc123"
  7. @bergie bergie revised this gist May 19, 2011. 1 changed file with 8 additions and 0 deletions.
    8 changes: 8 additions & 0 deletions blog.coffee
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,11 @@
    # Create Express server that uses some template engine (jade, ejs,
    # whatever) to render an index page
    # Create a static folder
    # Create a route for `/blog/id` that only accepts digits
    # Create a "fake database" (array) of blogs, and use middleware to
    # validate that ID is valid
    # Create a view for the blog post
    # Use a view partial to a preview blog posts on an index page
    express = require "express"

    blogPosts = [
  8. @bergie bergie revised this gist May 19, 2011. 5 changed files with 63 additions and 0 deletions.
    32 changes: 32 additions & 0 deletions blog.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    express = require "express"

    blogPosts = [
    title: "Hello, world"
    content: "<p>This is my very cool blog post</p>"
    ,
    title: "Second post"
    content: "<p>this post is even cooler</p>"
    ]
    app = express.createServer()

    app.use "/images", express.static "#{process.cwd()}/images"
    app.set "view engine", "jade"
    app.set "view options",
    layout: false

    app.get "/", (req, res, next) ->
    res.render "index",
    locals:
    posts: blogPosts
    as: "post"

    getBlog = (req, res, next) ->
    if blogPosts[req.params.id] is undefined
    throw new Error "Post not found"
    req.post = blogPosts[req.params.id]
    next()

    app.get "/blog/:id(\\d+)", getBlog, (req, res, next) ->
    res.render "post", req.post

    app.listen 8003
    11 changes: 11 additions & 0 deletions images/simple.css
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    body {
    background: url("viking.jpg");
    background-position: top left;
    background-repeat: no-repeat;
    padding-left: 300px;
    padding-top: 130px;
    }

    h1 a {
    color: black;
    }
    4 changes: 4 additions & 0 deletions views/index-post.jade
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    article
    h1
    a(href: "/blog/" + indexInCollection) #{post.title}
    div !{post.content}
    7 changes: 7 additions & 0 deletions views/index.jade
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    html
    head
    title My blog
    link(rel="stylesheet", href="/images/simple.css")
    body
    h1 My blog
    !=partial("index-post", posts)
    9 changes: 9 additions & 0 deletions views/post.jade
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    html
    head
    title #{title}
    link(rel="stylesheet", href="/images/simple.css")
    body
    article
    h1 #{title}
    div !{content}

  9. @bergie bergie revised this gist May 19, 2011. 1 changed file with 23 additions and 0 deletions.
    23 changes: 23 additions & 0 deletions expressError.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    express = require "express"

    app = express.createServer()

    app.error (err, req, res, next) ->
    if err instanceof NotFound
    res.statusCode = 404
    return res.end "404 not found"
    next err

    class NotFound extends Error
    constructor: (msg) ->
    @name = "NotFound"
    Error.call this, msg
    Error.captureStackTrace @, arguments.callee

    app.get "/doesntexist", (req, res, next) ->
    throw new NotFound

    app.get "/othererror", (req, res, next) ->
    throw new Error "Something is wrong!"

    app.listen 8003
  10. @bergie bergie revised this gist May 19, 2011. 1 changed file with 0 additions and 0 deletions.
    Binary file added images/viking.jpg
    Loading
    Sorry, something went wrong. Reload?
    Sorry, we cannot display this file.
    Sorry, this file is invalid so it cannot be displayed.
  11. @bergie bergie revised this gist May 19, 2011. 1 changed file with 46 additions and 0 deletions.
    46 changes: 46 additions & 0 deletions expressMiddlewares.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    # Create a middleware to detect a mobile browser and attach a boolean to the request
    # Create express app that servers links to images using staticProvider
    # Modify profiler to profile your app and write profile data to a log file
    # Create a middleware factory that sets the HTTP expires header based on roles
    express = require "express"
    fs = require "fs"

    app = express.createServer()

    browserDetector = (req, res, next) ->
    req.googled = false
    if req.headers['user-agent'].indexOf("Chromium") isnt -1
    req.googled = true
    next()

    mFactory = (role) ->
    expires = "Thu, 15 Apr 2010 20:00:00 GMT"
    if role is "permanent"
    expires = "Thu, 15 Apr 2150 20:00:00 GMT"
    (req, res, next) ->
    res.header "Expires", expires
    next()

    # True monkeypatching, override console.log to capture Profiler output
    originalLogger = console.log
    logFile = fs.createWriteStream "profile.log"
    console.log = (logVars...) ->
    originalLogger logVars...
    logVars.forEach (logVar) ->
    logFile.write "#{logVar}\n"

    app.use express.profiler()
    app.use browserDetector
    app.use "/images", express.static "#{process.cwd()}/images"

    app.get "/permanent", mFactory("permanent"), (req, res, next) ->
    res.end "This page never expires in your lifetime"

    app.get "/", (req, res, next) ->
    res.contentType "text/html"
    res.write "<img src='/images/viking.jpg' />"
    if req.googled
    return res.end "You're using a Chromium"
    res.end "You're a browser"

    app.listen 8003
  12. @bergie bergie revised this gist May 19, 2011. 1 changed file with 30 additions and 7 deletions.
    37 changes: 30 additions & 7 deletions expressRouting.coffee
    Original file line number Diff line number Diff line change
    @@ -2,26 +2,49 @@
    # Create a route that captures the product id after /product and returns it in response
    # Use a regex to restrict the ID param to 3 letters followed by 3-5 numbers
    # Route a route using regex that matches the entire route
    # Create a simple check for correct product IDs. If it fails, show a custom error page
    # Use app.all() to check user permission before showing (mock) edit controls on a page
    express = require "express"

    app = express.createServer()
    app.use express.logger
    format: ":method :url"

    app.get "/", (req, res) ->
    res.send "Front page"
    res.write "Front page"
    res.end()

    canUserEdit = ->
    true

    app.all "/products/*", (req, res, next) ->
    if canUserEdit()
    res.write "<button>Edit</button>"
    next()

    app.get "/products", (req, res) ->
    res.send "Our cool products"
    res.write "Our cool products"
    res.end()

    findProduct = (id) ->
    if id isnt "abc123"
    return false
    true

    app.get "/products/:id([a-z]{3}\\d{3})", (req, res, next) ->
    unless findProduct req.params.id
    return next()
    res.end "Product #{req.params.id}"

    app.get "/products/:id([a-z]{3}\\d{3})", (req, res) ->
    res.send "Product #{req.params.id}"
    app.get "/products/:id", (req, res) ->
    res.statusCode = 404
    res.end "Product #{req.params.id} not found"

    app.get "/services", (req, res) ->
    res.send "Our even cooler services"
    res.end "Our even cooler services"

    app.get /// (.*) ///, (req, res) ->
    app.get /// (.*) ///, (req, res, next) ->
    console.log "Got regex route #{req.url}, forwarding"
    req.next()
    next()

    app.listen 8003
  13. @bergie bergie revised this gist May 19, 2011. 1 changed file with 27 additions and 0 deletions.
    27 changes: 27 additions & 0 deletions expressRouting.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    # Create an express app with routes /, /products and /services
    # Create a route that captures the product id after /product and returns it in response
    # Use a regex to restrict the ID param to 3 letters followed by 3-5 numbers
    # Route a route using regex that matches the entire route
    express = require "express"

    app = express.createServer()
    app.use express.logger
    format: ":method :url"

    app.get "/", (req, res) ->
    res.send "Front page"

    app.get "/products", (req, res) ->
    res.send "Our cool products"

    app.get "/products/:id([a-z]{3}\\d{3})", (req, res) ->
    res.send "Product #{req.params.id}"

    app.get "/services", (req, res) ->
    res.send "Our even cooler services"

    app.get /// (.*) ///, (req, res) ->
    console.log "Got regex route #{req.url}, forwarding"
    req.next()

    app.listen 8003
  14. @bergie bergie revised this gist May 19, 2011. 1 changed file with 11 additions and 12 deletions.
    23 changes: 11 additions & 12 deletions asyncwebfetch.coffee
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,12 @@ async = require "async"
    http = require "http"
    fs = require "fs"

    fetchPage = (options, callback) ->
    fetchPage = (path, host, callback) ->
    options =
    host: host or "www.midgard-project.org"
    port: 80
    path: path
    method: "GET"
    client = http.request options, (results) ->
    content = ""
    results.on "data", (chunk) ->
    @@ -12,27 +17,21 @@ fetchPage = (options, callback) ->

    client.end()

    genOptions = (path) ->
    host: "www.midgard-project.org"
    port: 80
    path: path
    method: "GET"

    async.parallel [
    (callback) ->
    fetchPage genOptions("/"), callback
    fetchPage "/", null, callback
    ,
    (callback) ->
    fetchPage genOptions("/documentation/midcom/"), callback
    fetchPage "/documentation/midcom/", null, callback
    ,
    (callback) ->
    fetchPage genOptions("/download/"), callback
    fetchPage "/download/", null, callback
    ,
    (callback) ->
    fetchPage genOptions("/updates/"), callback
    fetchPage "/updates/", null, callback
    ,
    (callback) ->
    fetchPage genOptions("/midcom-login-"), callback
    fetchPage "/midcom-login-", null, callback
    ,
    ], (err, results) ->
    file = fs.createWriteStream "foo.txt"
  15. @bergie bergie revised this gist May 18, 2011. 1 changed file with 28 additions and 0 deletions.
    28 changes: 28 additions & 0 deletions proxy.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    http = require "http"

    fetchPage = (path, response, callback) ->
    options =
    host: "falsyvalues.com"
    port: 80
    path: path
    method: "GET"
    client = http.request options, (res) ->
    response.statusCode = res.statusCode

    for header, value of res.headers
    response.setHeader header, value

    res.on "data", (chunk) ->
    response.write chunk
    res.on "end", ->
    callback "", response

    client.end()

    server = http.createServer (req, res) ->
    console.log "Got request #{req.url}"

    fetchPage req.url, res, (err, response) ->
    response.end

    server.listen 8003, "127.0.0.1"
  16. @bergie bergie revised this gist May 18, 2011. 3 changed files with 51 additions and 0 deletions.
    49 changes: 49 additions & 0 deletions asynchttppost.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    http = require "http"
    async = require "async"
    fs = require "fs"

    options =
    host: "127.0.0.1"
    port: 8003
    path: "/"
    method: "POST"

    postData = (data, callback) ->
    client = http.request options, (results) ->
    results.setEncoding "utf-8"
    content = ""
    results.on "data", (ret) ->
    content += ret
    results.on "end", ->
    callback null, content

    client.write data
    client.end()

    server = http.createServer (req, res) ->
    req.setEncoding "utf-8"
    req.on "data", (content) ->
    console.log "DATA: #{content}"

    res.writeHead 200,
    'Content-Type': 'text/plain'
    res.end "Hey there"

    data = ""
    async.auto
    start_server: (callback) ->
    server.listen options.port, options.host, ->
    callback null
    read_first: (callback) ->
    fs.readFile "first.txt", "utf-8", (err, content) ->
    data += content
    callback err, content
    read_second: (callback) ->
    fs.readFile "second.txt", "utf-8",(err, content) ->
    data += content
    callback err, content
    post_to_server: ["start_server", "read_first", "read_second", (callback) ->
    postData data, (err, retval) ->
    server.close()
    callback
    ]
    1 change: 1 addition & 0 deletions first.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    First file
    1 change: 1 addition & 0 deletions second.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Second file
  17. @bergie bergie revised this gist May 18, 2011. 1 changed file with 41 additions and 0 deletions.
    41 changes: 41 additions & 0 deletions asyncwebfetch.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    async = require "async"
    http = require "http"
    fs = require "fs"

    fetchPage = (options, callback) ->
    client = http.request options, (results) ->
    content = ""
    results.on "data", (chunk) ->
    content += chunk
    results.on "end", ->
    callback "", content

    client.end()

    genOptions = (path) ->
    host: "www.midgard-project.org"
    port: 80
    path: path
    method: "GET"

    async.parallel [
    (callback) ->
    fetchPage genOptions("/"), callback
    ,
    (callback) ->
    fetchPage genOptions("/documentation/midcom/"), callback
    ,
    (callback) ->
    fetchPage genOptions("/download/"), callback
    ,
    (callback) ->
    fetchPage genOptions("/updates/"), callback
    ,
    (callback) ->
    fetchPage genOptions("/midcom-login-"), callback
    ,
    ], (err, results) ->
    file = fs.createWriteStream "foo.txt"
    results.forEach (result) ->
    file.write result
    file.end()
  18. @bergie bergie revised this gist May 18, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion README.md
    Original file line number Diff line number Diff line change
    @@ -1 +1 @@
    Some exercises from the Falsy Values workshops
    Some exercises from the [Falsy Values](http://falsyvalues.com/) workshops. [Liveblogs](http://www.qaiku.com/go/blzq/).
  19. @bergie bergie revised this gist May 18, 2011. 6 changed files with 17 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions clientserver.coffee
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,7 @@
    # Create a web server
    # Create an HTTP client in the same file
    # POST data to your server
    # Output the POST data
    http = require "http"

    options =
    4 changes: 4 additions & 0 deletions express.coffee
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,13 @@
    # Create an expressjs server
    express = require "express"

    app = express.createServer()
    app.use express.logger
    format: ":method :url"
    app.use express.cookieParser()

    # Serve two different pages based on GET parameter "page"
    # Set a cookie on the client
    app.get "/", (req, res) ->
    if req.query.page is "1"
    res.cookie "foo", 1
    @@ -15,6 +18,7 @@ app.get "/", (req, res) ->
    res.clearCookie "foo"
    res.send "Index"

    # Create a redirect from /old to /new
    app.get "/old", (req, res) ->
    res.redirect "/new"

    2 changes: 2 additions & 0 deletions fish.coffee
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    # Create CommonJS module "fish"
    # Provide functions to swim, mouthbreath, flap around
    exports.swim = ->
    "swims"

    5 changes: 5 additions & 0 deletions http.coffee
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,8 @@
    # Create the basic Node.js http server
    # Modify it to return some other text
    # Make it return HTML
    # Return the user-agent
    # Return different text for at least two different browsers
    http = require 'http'

    browserSpecific = (agent) ->
    1 change: 1 addition & 0 deletions httpclient.coffee
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    http = require "http"

    # Fetch the nytimes.com and output to console
    options =
    host: "www.nytimes.com"
    port: 80
    1 change: 1 addition & 0 deletions useFish.coffee
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    # Import "Fish" module into another file and call the methods
    fish = require("./fish")
    console.log require.paths

  20. @bergie bergie revised this gist May 18, 2011. 6 changed files with 94 additions and 0 deletions.
    27 changes: 27 additions & 0 deletions clientserver.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    http = require "http"

    options =
    host: "127.0.0.1"
    port: 8003
    path: "/"
    method: "POST"

    server = http.createServer (req, res) ->
    console.log "Got request"
    req.setEncoding "utf-8"
    req.on "data", (content) ->
    console.log "DATA: #{content}"

    res.writeHead 200,
    'Content-Type': 'text/plain'
    res.end "Hey there"

    server.listen options.port, options.host, ->

    client = http.request options, (results) ->
    results.setEncoding "utf-8"
    results.on "data", (content) ->
    console.log content

    client.write "Foo bar baz"
    client.end()
    24 changes: 24 additions & 0 deletions express.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    express = require "express"

    app = express.createServer()
    app.use express.logger
    format: ":method :url"
    app.use express.cookieParser()

    app.get "/", (req, res) ->
    if req.query.page is "1"
    res.cookie "foo", 1
    return res.send "First page, cookie is #{req.cookies.foo}"
    if req.query.page is "2"
    res.cookie "foo", "2"
    return res.send "Second page"
    res.clearCookie "foo"
    res.send "Index"

    app.get "/old", (req, res) ->
    res.redirect "/new"

    app.get "/new", (req, res) ->
    res.send "This is the new page"

    app.listen 8003
    9 changes: 9 additions & 0 deletions fish.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    exports.swim = ->
    "swims"

    exports.mouthBreath = ->
    "doesn't know how to mouthbreath"

    exports.flapAround = ->
    "happily flaps around"

    14 changes: 14 additions & 0 deletions http.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    http = require 'http'

    browserSpecific = (agent) ->
    if agent.indexOf("Chromium") isnt -1
    return "an Agent of Google"
    "something I don't recognize"

    server = http.createServer (req, res) ->
    res.writeHead 200,
    'Content-Type': 'text/html'
    'X-Powered-By': 'Coffee'
    res.end "<h1>I'm learning Node</h1>
    <p>And you're #{browserSpecific(req.headers['user-agent'])}"
    server.listen 8003, '127.0.0.1'
    14 changes: 14 additions & 0 deletions httpclient.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    http = require "http"

    options =
    host: "www.nytimes.com"
    port: 80
    path: "/"
    method: "GET"

    request = http.request options, (results) ->
    results.setEncoding "utf-8"
    results.on "data", (content) ->
    console.log content

    request.end()
    6 changes: 6 additions & 0 deletions useFish.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    fish = require("./fish")
    console.log require.paths

    console.log "Fish #{fish.swim()}"
    console.log "Fish #{fish.mouthBreath()}"
    console.log "Fish #{fish.flapAround()}"
  21. @bergie bergie created this gist May 18, 2011.
    1 change: 1 addition & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Some exercises from the Falsy Values workshops