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

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.

Related

How do I make Node.js reference the CSS for my HTML

I am trying to create a Turn Based strategy game like EU4 in JS. I would like to include multiplayer functionality but I want to understand why this keeps happening: When I run my app through node it seems to be that it only shows the bare HTML and not the CSS. Please help.
Code Below:
var express = require('express')
var app = express()
var serv = require('http').Server(app)
var port = 2000
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html')
})
app.use('/client', express.static(__dirname + '/client'))
serv.listen(port)
console.log('Colonial Warfare server => initialized!')
console.log('CWserver HostPort: ' + port)
var io = require('socket.io') (serv,{})
io.sockets.on('connection', function(socket) {
console.log('socket connection')
})
When your browser send the http request "/" you return your html that links to "/css/gameStyle.css".
You can either move your css folder to the client folder and change the link to "/client/css/gameStyle.css".
Or you can serve your css folder on the node app app.use(express.static('css'))
You need to serve the static CSS files by replacing the get for your index.html with the following line:
app.use(express.static('public'))
Change 'public' to 'client' if the CSS is next to your index.HTML.
Details here:
https://expressjs.com/en/starter/static-files.html
--EDIT--
As the index.html includes the css like "/css/filename.css" you have to host it like this:
app.use(express.static('css'))
or you change the references to your stylesheets to /client/css/filename.css in your html file.
Whenever you access an (for express) unknown path, express returns the index.html file.

Express / Node sendFile weird behavior

I'm trying to combine Node/Express and serve React files but its not working as desired.
server.js (my own REST API)
var express = require('express')
var app = express()
var public = __dirname + "/../frontend/build";
app.use(express.static(public));
app.get('/', (req, res) => {
res.sendFile(public + "/index.html");
});
app.get('/api/g', (req, res) => {
res.send("Test")
})
app.listen(3001);
My React build is in the public variable location.
Now when I go to localhost:3001 where my node server runs, I get this page
Page
but the issue is when I go to localhost:3001/api/g I still get the same page. Meaning, I dont get my "res.send" part, I have no idea why this is happening. Can anyone familiar with Node/Express help me out?

express js static file from different path than root

I have a page asking for these files
<link rel="stylesheet" href="/vendor/css/style.css">
<script type="text/javascript" src="/vendor/js/app.js"></script>
and I've set up the express static route as follows
express = require 'express'
app = express()
app.use '/vendor/js', express.static './node_modules/framework/'
app.use '/vendor/css', express.static './otherFramework/'
app.get '/page/:num', (req, res) ->
page = parseInt req.params.num, 10
res.render 'list', #list is a jade file that extends a common layout.jade, the same as the '/' route
start: page
end: ++page
return
when I open the page '/' everything works fine, but now I want to implement another MVC-like route like '/page/:num', and express is asked this new route as base path for my requested external files, ex: (from the server log)
/page/1/vendor/css/style.css - 200
and this obviously doesn't work.
How can I tell express to search in the root? I tried to use a ~ before the path but it didn't work.
in the app.js (main file) file,before application routes, add these lines :
app.get('*/vendor/css/style.css', function (req, res) {
res.sendFile(__dirname + '/vendor/css/style.css');
});
app.get('*/vendor/js/app.js', function (req, res) {
res.sendFile(__dirname + '/vendor/js/style.js');
});
#akram-saouri 's answer was almost exact: I ended up using this configuration:
app.use '*/vendor/js', express.static './node_modules/framework/'
app.use '*/vendor/css', express.static './otherFramework/'
for all the app and it worked like a charm

How do I serve a static file using Node Express?

I was having trouble settings up a very basic static file sever using express with Node.js. I set up a simple server.js but cannot see any files when I load the URL localhost:9000 in my web browser.
All I see is a page saying: Cannot get /
var express = require('express');
var app = express();
app.use(function(req, res, next) {
next();
});
app.use(express.static(__dirname));
app.listen(9000);
Simply you're exposing nothing. Do you have, for example, an index.html file? Try this:
app.get("/", function(req, res) {
res.sendfile("index.html");
});
Did you go through the NodeSchool workshoppers? They have step-by-step examples that cover this and more.
Here is the workshop for Express.
Here is my solution for the 'static' question in the workshop.
var express = require('express')
var app = express()
app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));
app.use(require('stylus').middleware(__dirname + '/public'));
app.post('/form', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
})
app.listen(process.argv[2])
Express does not create a directory listing. Even thought it does not list the files in the directory, it does serve them up when hitting them in the web browser.
Point the browser to the actual file:
http://localhost:9000/public/test.html
Originally I found this confusing because I had expected the express server to list directories; when seeing "something"... a page that said "Cannot get /" I assumed that page would normally have a list of files.

Basic webserver with node.js and express for serving html file and assets

I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.

Categories

Resources