maudulus
maudulus

Reputation: 11025

How to link a javascript file to an html page using express and nodeJS

My Node.js app is very simple, but I am having difficulty linking my JavaScript file to it. Normally, you would just put the script in the header. That doesn't work with Node, apparently, so I have tried to link it through sendFile and some other methods, but none have worked.

My JavaScript is simply:

var express = require('express');
var app = express();

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/index.html');
    res.send()
});
app.listen(8888)

My HTML is also simple:

<html>
<head>
    <title>Charter</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <div id="container" style="width:100%; height:400px;"></div>
    <button id="button" class="autocompare" onclick="plotNewChart()">Add series</button>
    <script type="text/javascript">
         $(function () { $('#container').highcharts({ chart: { events: { addSeries: function () { var label = this.renderer.label('A series was added, about to redraw chart', 100, 120).attr({ fill: Highcharts.getOptions().colors[0], padding: 10, r: 5, zIndex: 8 }) .css({ color: '#FFFFFF' }) .add(); setTimeout(function () { label.fadeOut(); }, 1000); } } }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }); });
    </script>
</body>
</html>

What I want to do is link another file, myJS.js. I don't know how to do that without the typical <script src="myJS.js"></script>.

Upvotes: 9

Views: 40266

Answers (1)

moonthug
moonthug

Reputation: 406

You need to setup your Express server to serve static files. At the moment, it appears to only serve the '/' route.

Just before you setup your routing, add the line below. You can then serve up static assets from a 'public' folder relative to where your script it.

app.use(express.static(path.join(__dirname, 'public')));

So if you put your myJS.js in public/js/myJS.js you can then reference it like so

<script src="/js/myJS.js"></script>

More info in the docs: http://expressjs.com/api.html#express.static

Upvotes: 23

Related Questions