Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Falsy Values tutorials
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
]
async = require "async"
http = require "http"
fs = require "fs"
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) ->
content += chunk
results.on "end", ->
callback "", content
client.end()
async.parallel [
(callback) ->
fetchPage "/", null, callback
,
(callback) ->
fetchPage "/documentation/midcom/", null, callback
,
(callback) ->
fetchPage "/download/", null, callback
,
(callback) ->
fetchPage "/updates/", null, callback
,
(callback) ->
fetchPage "/midcom-login-", null, callback
,
], (err, results) ->
file = fs.createWriteStream "foo.txt"
results.forEach (result) ->
file.write result
file.end()
# 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 = [
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
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
# 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 =
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()
cluster = require "cluster"
app = require("./clusterWorker").server
workers = cluster app
workers.use cluster.debug()
workers.listen 8003
express = require "express"
app = express.createServer()
app.get "/hello/:name", (req, res, next) ->
res.send "Hello, #{req.params.name}"
exports.server = app
# 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
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"
# Create a redirect from /old to /new
app.get "/old", (req, res) ->
res.redirect "/new"
app.get "/new", (req, res) ->
res.send "This is the new page"
app.listen 8003
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
# 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
# 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
# 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.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.end "Our cool products"
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", (req, res) ->
res.statusCode = 404
res.end "Product #{req.params.id} not found"
app.get "/services", (req, res) ->
res.end "Our even cooler services"
app.get /// (.*) ///, (req, res, next) ->
console.log "Got regex route #{req.url}, forwarding"
next()
app.listen 8003
First file
# Create CommonJS module "fish"
# Provide functions to swim, mouthbreath, flap around
exports.swim = ->
"swims"
exports.mouthBreath = ->
"doesn't know how to mouthbreath"
exports.flapAround = ->
"happily flaps around"
# 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) ->
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'
http = require "http"
# Fetch the nytimes.com and output to console
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()
article
h1
a(href: "/blog/" + indexInCollection) #{post.title}
div !{post.content}
html
head
title My blog
link(rel="stylesheet", href="/images/simple.css")
body
h1 My blog
!=partial("index-post", posts)
html
head
title #{title}
link(rel="stylesheet", href="/images/simple.css")
body
article
h1 #{title}
div !{content}
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"
Second file
body {
background: url("viking.jpg");
background-position: top left;
background-repeat: no-repeat;
padding-left: 300px;
padding-top: 130px;
}
h1 a {
color: black;
}
li.own {
color: #c0c0c0;
}
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", ->
jQuery("#input").attr "disabled", false
socket.on "message", (msg) ->
addItem msg
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"
addItem jQuery("#input").val(), true
socket.send jQuery("#input").val()
jQuery("#input").val ""
(function() {
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() {
return jQuery("#input").attr("disabled", false);
});
socket.on("message", function(msg) {
return addItem(msg);
});
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");
addItem(jQuery("#input").val(), true);
socket.send(jQuery("#input").val());
return jQuery("#input").val("");
});
});
}).call(this);
express = require "express"
io = require "socket.io"
net = require "net"
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
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
forwardMessage msg, client
client.on "disconnect", ->
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"
# Import "Fish" module into another file and call the methods
fish = require("./fish")
console.log require.paths
console.log "Fish #{fish.swim()}"
console.log "Fish #{fish.mouthBreath()}"
console.log "Fish #{fish.flapAround()}"
@gbraad

This comment has been minimized.

Copy link

commented May 30, 2011

@victusfate

This comment has been minimized.

Copy link

commented May 30, 2011

These will come in handy as I'm learning CoffeeScript, thanks Bergie.

Having trouble embedding (gist image is hosed) or editing my fork ("Contents can't be stored in subdirectories"), any idea why?

update: hah, the file names had parent folders from your original gist, whoops.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.