CoffeScript: not required to be recognized when runninjg from browser

I am trying to run this piece of code from http://coffeescriptcookbook.com by embedding it in 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 a file called client.coffe, and when I run it with the coffee: coffee client.coffe command it works fine and connects to the server, but when I insert it into the html file and open it, I get this error: Missed ReferenceError: require is undefined.

My html script tags look 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?

+6
source share
2 answers

This will not work in the browser.

The first problem: the browser is not allowed to connect to other servers or ports than for security reasons. In addition, you do not get real sockets, just HTTP.

The second problem: require is the node.js command, which you can use only in node.js (i.e. when you run the javascript file using the node command or the coffeescript file using the coffee command). The net module is owned by node.js and will never work this way in a browser.

If you want to talk to the server in real time from within the browser, I recommend the socket.io module, which uses web files, flash files and HTTP (they can be used from the browser).

+5
source

You can use require in a browser with wrappers such as node-browserify . However, all the problems noted by @thejh are correct, so you have to rethink your code.

+2
source

Source: https://habr.com/ru/post/902027/


All Articles