Kahsius Kahsius - 3 months ago 35
Javascript Question

External js in an EJS template

I have some trouble using EJS. I would like to use a javascript file in my template, but I can't find the right way to implement it, here is my code so far :

game.ejs :

<!DOCTYPE html>
<html>
<head>
<title>D-D-D-Duel !!!</title>
<link rel="stylesheet" type="text/css" href="/view/css/game.css">
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src= "/actions_client.js"></script>
</head>

<body>
<style type="text/css">
...
</style>
// My body
</body>
</html>


Whatever path I try for my script /actions_client.js, the view can't find it while loading in my browser. It's maybe a problem with node.js I also use, I don't know where to put my script in order to make my view find it (what and/or where is the folder localhost:8080/ ?)

Regards

EDIT : Something that I don't understand neither is how can the view find socket.io/socket.io/js while I don't find it when I search on my computer ?

EDIT : Here is my code in my node file by the way :

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

Answer

Use

app.use(express.static(__dirname + '/ressources'));

to set the 'localhost:8080' folder as ./ressource.

__dirname is automatically generated by nodejs and contain the filepath to the folder in which is stored your node.js script.

However, /socket.io/socket.io.js will be in __dirname + '/socket.io/socket.io.js'.

Comments