Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeScript: require not recognized when runninjg from the browser

Tags:

coffeescript

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?

like image 514
Esteban Angee Avatar asked Nov 21 '11 17:11

Esteban Angee


2 Answers

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).

like image 104
thejh Avatar answered Sep 20 '22 06:09

thejh


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.

like image 22
tokland Avatar answered Sep 21 '22 06:09

tokland