I am trying to make an app the generates 'live' graphs of Twitter word counts, basically trying to extend and exercise in Chapter 14 of NodeJS in 24 Hours. I decided to use 'Rickshaw' and I thought I'd start with simply getting a simple example working. However, while I can get a simple html page to load, I can't get a graph to display. Firefox debug indicates: "ReferenceError: Rickshaw is not defined [Break On This Error] graph = new Rickshaw.Graph( { " . That means that there is a referencing error but after a couple of hours of googling and reading, I'm not seeing it. The directory structure is correct; npm installed all modules correctly, no errors. Can anyone see what I'm missing?
Note: I am new to JS/Node and while the book is working in Express 2.x, I have been working in Express 3.x, so not sure if I've got the translation correct in all cases. The code is as follows:
package.json
{
"name":"socket.io-twitter-example",
"version": "0.0.1",
"private": "true",
"dependencies": {
"express": ">=2.5.4",
"rickshaw": ">=1.1.0"
}
}
app.js
var express = require('express'),
rickshaw = require('rickshaw'),
app = express(),
http = require('http'),
server = http.createServer(app)
server.listen(3000);
app.get('/', function (req,res) {
res.sendfile(__dirname + '/index.html');
});
index.html
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="UTF-8" />
<title>Socket.IO Twitter Example</title>
</head>
<body>
<h1>Rickshaw Example</h1>
<div id="chart"></div>
<ul class="tweets"></ul>
<script type="text/javascript" src="node_modules/rickshaw/vendor/d3.v2.js"></script> //don't think "node_modules/" is required, but doesn't work without either
<script type="text/javascript" src="node_modules/rickshaw/rickshaw.min.js"></script>
<script>
graph = new Rickshaw.Graph( {
element: document.querySelector("#chart"),
width: 285,
height: 180,
series: [{
color: 'steelblue',
data: [
{ x: 0, y: 40 },
{ x: 1, y: 49 },
{ x: 2, y: 38 },
{ x: 3, y: 30 },
{ x: 4, y: 32 } ]
}]
});
graph.render();
</script>
</body>
</html>
You need to configure express.static
middleware so that express
knows where to look for static resources like js and css files:
app.use(express.static( __dirname + '/public'));
Its common to put such resources into a public
folder (as shown in the example above) or static
folder.
If you create a public
folder and organize it like
app.js
public
rickshaw
vendor
d3.v2.js
rickshaw.min.js
then you'll be able to have the files correctly loaded in your html using
<script type="text/javascript" src="/rickshaw/vendor/d3.v2.js"></script>
<script type="text/javascript" src="/rickshaw/rickshaw.min.js"></script>
See this section of the express
docs for more info on and examples of middleware.