- Getting Started
- The now object
Quick "Hello World" Example
Once NowJS is installed on your server, creating your first application is simple:
Copy this code into helloworld_server.js
var html = require('fs').readFileSync(__dirname+'/helloworld.html');
var server = require('http').createServer(function(req, res){
res.end(html);
});
server.listen(8080);
var nowjs = require("now");
var everyone = nowjs.initialize(server);
everyone.now.distributeMessage = function(message){
everyone.now.receiveMessage(this.now.name, message);
};
Copy this code into helloworld.html in the same directory
<!DOCTYPE html>
<html lang="en">
<head>
<title>nowjs test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="/nowjs/now.js"></script>
<script>
$(document).ready(function(){
now.receiveMessage = function(name, message){
$("#messages").append("<br>" + name + ": " + message);
}
$("#send-button").click(function(){
now.distributeMessage($("#text-input").val());
$("#text-input").val("");
});
now.name = prompt("What's your name?", "");
});
</script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="text-input">
<input type="button" value="Send" id="send-button">
</body>
</html>
You've just created a chat server
Let's test it!
Run node helloworld_server.js in your terminal.
Navigate your browser to http://localhost:8080.
Try it with two tabs or even different browsers for that hot realtime chat action.
Having trouble?
We're always available to help via email team@nowjs.com. Also try our mailing list / Google group. You can also ask us questions on IRC #nowjs on Freenode
Next
Next: The now Object
