jleach
jleach

Reputation: 7792

Client files location with node server?

I'm trying a stupid simple chat app per here: http://socket.io/get-started/chat/

All good, except I figured I'd split the css and js out of the index.html file into separate files. So I have a project folder that looks like this:

/myProject
  index.js
  index.html
  /node_modules
     /express
     /socket.io

So in the myproject folder, I created client folder and put an app.css and app.js in there:

/myProject
  /client
    app.css
    app.js

and switched my html:

<link rel="stylesheet" href="/client/app.css" />
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/client/app.js"></script>

I restart the node server and run the index, however my chrome inspector has 404s on the /client files.

I tried moving the client folder into the node_modules folder (thinking that this must be where the html is getting it's socket.io ref from), but that doesn't do it.

When the node server starts, what local folder does it serve from (using Windows here), and how do I add other client side files? I'm not supposed to be listing all these in the package dependencies am I?

Per the answer below, yes, using express (4.10.2)

Getting error:

reference error: express is not defined

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

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

io.on('connection', function(socket) {
    console.log('user connected');
    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
    socket.on('chat message', function(msg) {
        console.log('message: ' + msg);
    });
});

http.listen(3000, function() {
    console.log('listening on *.3000');
});

Upvotes: 1

Views: 2019

Answers (1)

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

Im assuming you using express.

So in order to serving static files in Express you need this

https://expressjs.com/en/starter/static-files.html

app.use(express.static('client'));

Hope this helps.

Upvotes: 3

Related Questions