Question

I'm having trouble getting the now.js chat client tutorial to work. (I've also followed this video almost exactly).

server.coffee:

fs = require 'fs'
http = require 'http'
now = require 'now'

server = http.createServer (req, res) ->
    fs.readFile(
        'index.html'
        (err, data) ->
            res.writeHead(
                200
                    'Content-Type': 'text/html'
                )
            res.end(data)
        )
server.listen 8080

everyone = now.initialize(server)

everyone.now.distributeMessage = (msg) ->
    everyone.now.receiveMessage(@.now.name, msg)

index.html:

<html>
    <head>
        <title>nowjs title</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="https://raw.github.com/Flotype/now/master/lib/now.js"></script>

        <script type="text/javascript">
        $(document).ready(function() {
            now.name = prompt("What's your name?", "");
            now.receiveMessage = function(name, msg) {
              return $("<div></div>").text("" + name + ": " + msg).appendTo("#msg");
            };
            return $("#send-button").click(function() {
              now.distributeMessage($("#text-input").val());
              return $("#text-input").val("");
            });
          });
        </script>
    </head>

    <body>
        <div id="msg"></div>

        <input type="text" id="text-input">
        <input type="button" value="Send" id="send-button">
    </body>
</html>

When I load up the server with node server.js,

I get an error that says "require not defined" on line 1 of now.js. Consequently, the client side code can't find the variable 'now'.

I understand that 'require' is a node function, but how do I get the client to understand that?

Any help will be appreciated.

Was it helpful?

Solution

The file you're including in your client source (../Flotype/now/master/lib/now.js) is the Node server side code that is included in your node process when calling now = require 'now'.

So changing your included client source file from .../Flotype/now/master/lib/now.js to /nowjs/now.js will fix your problem.

Where does this /nowjs/now.js file come from?

When using NowJS (and many other npm packages that do client/server communication) you extend the server object. This is done with the line everyone = now.initialize(server) (Code Here).

What the initialize function does is wrap your server with the fileServer (Code Here) class in NowJS. This adds a resource under the "folder" nowjs which serves the client now.js file.

OTHER TIPS

I got this error when trying to run nodejs file with js command instead of node. Eg: if the nodejs file name is test.js, I was doing

js test.js

instead of node test.js

I hope this helps too for people searching for this error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top