now.js - Hello World example - "require not defined" - node.js

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.

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.

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.

Related

Uncaught reference error require is not defined

I'm trying to use an html page in order to test the connection with my server.
I've got no problem with my server.js
var http = require('http');
var url = require("url");
// Chargement de socket.io
var io = require('socket.io').listen(server);
var server = http.createServer(function(req, res) {
var page = url.parse(req.url).pathname;
// Quand un client se connecte, on le note dans la console
});
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
});
server.listen(8080);
My client should is an html page here
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communication test with socket.io !</h1>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://localhost:8000/server_node/node_modules/socket.io/lib/socket.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
</script>
</body>
</html>
Problem is, when I load the html client, I've got this error
socket.js:6 Uncaught ReferenceError: require is not defined
at socket.js:6
I'm not trying to implement a real client, I just want a simple page in order to do some connection test.
Thanks for your help
EDIT: Problem fixed, it was all because I wasn't loading the html file from the serverlike this fs.readFile('./ClientTest.html', 'utf-8', function(error, content) {
As this is just used to do some test, it's fine if it works this way; the client side will be with an other platform.
Sorry for that useless issue :(
You appear to be importing the server-side library on the client, you want to be importing the client-side one.
As per the docs, this is automatically served when socket.io runs on the server which you can import via
<script src="/socket.io/socket.io.js" />

execute server side script for file creations

Using node.js, I am developing a small web application where want to create a file on server with a button click on browser. I have a small file "file.js" in public folder as below,
var fs = require("fs");
console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully! checked");
console.log("Let's read newly written data");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
It works fine when i execute this as "node file.js" and creates a input.txt. Calling this file in html page where trying to call through ajax call as below,
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
console.log(' firstpage ');
function readTextFile(){
console.log(' in function readTextFile ');
var dataString;
$.ajax({
type: "GET",
url: "file.js",
data: dataString,
success: function(err,data){
alert( "Data Saved: " + data );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
</script>
</head>
<body>
<p class="auto-style1"><strong>Welcome to MyPage</strong></p>
<div >
<input class="myButton" type="button" onclick="readTextFile()" value="Submit" />
</div>
</body>
</html>
Pressing the button gives me error,
ReferenceError: require is not defined
at eval (eval at <anonymous> (jquery.min.js:2), <anonymous>:1:10)
at eval (<anonymous>)
at jquery.min.js:2
at Function.globalEval (jquery.min.js:2)
at text script (jquery.min.js:4)
at Pc (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.b (jquery.min.js:4)
please help , where i am making mistake and how to fix. Many thanks in advance.
A couple things to help you understand what's going wrong:
1) Running "node file.js" is executing your JavaScript file on your server in a node.js environment.
2) When you run your webpage and fetch and execute file.js, your browser is running file.js using its own JavaScript interpreter directly in the browser.
3) node.js has additional features for server side applications, one being the "require" syntax. This allows server side applications to include other JavaScript files rather than loading them in some HTML with a script src tag
4) node.js also provides some modules that are particularly useful for server side applications, such as "fs"
Your file.js looks like it's coded specifically to be run on the server side rather than on a browser client. It uses node.js syntax and even manipulates a file on the file system
You will need to run a node.js server (express.js being one popular choice) that can execute your file.js via some API endpoint. Then change your browser code to call the endpoint instead of trying to fetch and execute file.js directly in the browser

My ajax call to node script not working

servercode.js
var express = require('express');
var app = express();
app.get("/abc",function(req, res) {
res.send("Hello");
});
clientcode.html
<html>
<head>
<script type="text/javascript">
$.get("/abc", function(string) {
alert(string);
})
</script>
</head>
<body>
There is no as such body of this. Its just works. :)
</body>
</html>
I want to call the servercode.js script from my client. Both files are on the node server. So that I receive the alert Hello in my client.
Though my main aim is to call a function periodically that would be written in servercode.js file. But for the time being I am not even being able to receive the hello response from the server and my files are in firebase hosting.
I hope I am clear with my question.
Help me on this!! Thank you very much.

socket.io node.js server "debug: destroying non-socket.io upgrade" message

I have a node.js socket server using socket.io.
I'm building a firefox addon, where I load a pageworker. The html in the following page is as follows:
<html>
<head>
<script type="text/javascript">
//THIS DOESN'T WORK
var exampleSocket = new WebSocket("ws://someip:port");
exampleSocket.onopen = function (event) {
console.log("socket opened!");
};
//THIS WORKS
var exampleSocketa = new WebSocket("ws://echo.websocket.org");
exampleSocketa.onopen = function (event) {
console.log("socket to echo opened!");
};
</script>
</head>
<body>
</body>
</html>
I can open a websocket to echo.websocket.org, but not my own server. I get a "debug: destroying non-socket.io upgrade" message. I can switch it off with the option: { 'destroy upgrade': false }, but then I see no debug output from server, and no connection is made.
What am I doing wrong? How can I get a socket open to my socket.io server?
So after some more googling, it turns out that I need to require socket.io on the client side. Even though socket.io uses websockets, it prefers talking to itself.

How to share common function between server and client using node.js

Following are the structure of my application
Inside prototype.js file i have following code:
(function(exports) {
exports.foo = function() {
return 'bar';
};
})((typeof process === 'undefined' || !process.versions) ? window.common = window.common || {} : exports);
app.js contains
var express = require('express'),app = express(),server = require('http').createServer(app),io = require('socket.io').listen(server),port = 3000,path = require('path');
var common = require('common/prototype');
console.log(common.foo());
// listening to port...
server.listen(port);
//Object to save clients data
var users = [];
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendfile('/public/index.html');
});
index.html contains
<!doctype html>
<html lang="en">
<head>
<title>Socket.io Demo</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="/common/prototype.js"></script>
<script>
alert(window.common.foo()); //This line will gives me an error TypeError: window.common is undefined
</script>
</body>
</html>
Now i would like to print
Hello, I am bar from server and client as well.
Now i am able to print from server side using following line
var common = require('common/prototype');
console.log(common.foo());
But could not able to show alert on client side. could you please help me to find the root cause for the issue.
The root cause is that when you do <script src="/common/prototype.js"></script> in your HTML the file won't be fetched because the Express static middleware is only looking for files under your public folder.
A quick way to test this is to copy your prototype.js to your javascript folder inside public. Then update your script tag to reference the file as follows <script src="/javascripts/prototype.js"></script>
The thing to remember is that the JavaScript files that live under node_modules are not automatically available to the browser.

Resources