I am trying to run this piece of code taken from http://coffeescriptcookbook.com embedding it into an html.
net = require 'net'
domain = 'localhost'
port = 9001
connecting = (socket) ->
console.log "Connecting to real-time server"
connection = net.createConnection port, domain
connection.on 'connect', () ->
console.log "Opened connection to #{domain}:#{port}"
connecting connection
connection.on 'data', (data) ->
console.log "Received: #{data}"
connection.on 'end', (data) ->
console.log "Connection closed"
This code is in file named client.coffe and when i run it with the coffee command: coffee client.coffe it runs fine and connects to the server, but when I embbed it in a html file and open it i get this error: Uncaught ReferenceError: require is not defined.
My html script tags looks like this:
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"
type="text/javascript" charset="utf-8" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"
type="text/javascript" charset="utf-8"></script>
<script src="{% get_static_prefix %}functions.js"
type="text/javascript" charset="utf-8"></script>
<script src="{% get_static_prefix %}jquery.dajax.core.js"
type="text/javascript" charset="utf-8"></script>
<script src="{% get_static_prefix %}client.coffee"
type="text/coffeescript" charset="utf-8"></script>
Any ideas?
This won't work in the browser.
First issue: Stuff in the browser isn't allowed to connect to other servers or ports than it's coming from for security reasons. Also, you don't get real sockets, just HTTP.
Second issue: require
is a node.js command you'll only be able to use in node.js (that is, when you run a javascript file with the node
command or a coffeescript file with the coffee
command). The net
module belongs to node.js and will never work this way in the browser.
If you want to talk to the server in realtime from inside the browser, I recommend the socket.io
module which uses websockets, flashsockets and HTTP (those are usable from within the browser).
You can use require
in a browser with wrappers like node-browserify. However, all problems pointed out by @thejh are correct, so you'll have to rethink your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With