简体   繁体   中英

Loading .js files on client side with page served by Node JS

I have the following simple JS file, which will look familiar to anyone who's used Socket.IO with NodeJS and the Express framework:

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(8374);

// routing
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
});

In index.html , I have the following line of code:

<script src="/socket.io/socket.io.js"></script>

I have done some experimenting with pathnames and serving/mounting and I still don't really understand how this client-side line manages to work. The answer to this question says that by listening to the server , io handles all incoming Socket.IO requests.

...

My question is: Can this be done for other client-side JS files?

For example, is there some easy way to bundle up JQuery so that it can be handled in the same way? At the moment I can put the file in a folder like public and use Express' app.use() method so that in index.html I can include this line:

<script src="/public/jquery-1.9.1.js"></script>

Is there a way to manage JQuery as a dependency as we can with NodeJS?

I'm thinking the end result would look something like this:

SERVER-SIDE:

var jquery = require('jquery');

CLIENT-SIDE:

<script src="jquery/jquery-1.9.1.js"></script>

I'm not too sure about using modules to host specific files, but it would be more time-efficient to just host the file when it's requested:

app.get("/", function (req, res) {
    res.sendfile(__dirname + "/index.html");
});
app.get("/public/jquery-1.9.1.js", function (req, res) {
    res.sendfile(__dirname + "/public/jquery-1.9.1.js");
});

I don't use Express, so please excuse any mistakes.

In express 2.x many used to use "dynamicHelpers" for this. Something like this in your app.js

app.dynamicHelpers({
    scripts: function (){ 
      return ['/js/jquery.min.js', '/js/jquery.ui.min.js']
    }
})

In your layout using jade you'd do this.

- each s in scripts
    script(type='text/javascript', src= s)

Now app.dynamicHelpers has been removed so in express 3.x you'll need to either create a simple module for this or just do it inline. with app.use within your configuration or specific environment if need be. something like.

app.use(function (req, res, next){
   res.locals.scripts = ['/js/yourscript.js', '/js/yourotherscript.js']
   next();
}

Using it in the jade layout would be the same. If I'm understanding you correctly that would be one way to include these scripts. Personally I'd rather included them statically though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM