This is driving me crazy... while I have a working version of Express + Socket.io, I can't seem to reproduce it with out-of-the-box NPM installs in a new project folder. Can anyone point out what I'm missing...? Here's my process:
I create a node_modules
folder in my project directory (pwd
), then do:
npm install express
npm install socket.io
Running those two commands puts the packages in my project's node_modules
folder as expected. Now I set up my server with the following:
var express = require('express'),
server = express.createServer().use( express.static(__dirname+'./public') ).listen( 8080 ),
io = require('socket.io').listen(server);
My public
folder contains static assets for my application. My public index HTML page includes a script tag for:
<script src="/socket.io/socket.io.js"></script>
Finally, I run my server script and go to the application in a web browser. My static public files are all served properly, however I get a 404 for /socket.io/socket.io.js
. Now, I can swap in an express
package from another old project and have this whole system work. Somehow that package instance is configured differently, but I can't figure out how to reproduce that. The Express website mentions something about installing dependencies, although running npm install -d
doesn't seem to help (is there a specific pwd
that I need to be in while running npm install -d
?). I figure I must be missing something important about configuring a new Express instance after installing it with NPM.
Thanks for any and all insight!
Okay, so my example was actually an abbreviation of my code, and that example code does actually work. My real code with problems was a bit more cluttered, like so:
var server = express.createServer();
server
.use( server.router )
.use( express.static(__dirname+'/../public') )
.get('/api', function(req, res) {
res.write('API');
});
server.listen(8080);
var io = require('socket.io').listen(server);
I fixed the above code by doing the following:
server = server.listen(8080);
Apparently the listen
command wraps the server object with some additional functionality. My originally posted shorthand example actually does work because listen
is chained onto the final return into the server variable. Interesting little nuance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With