I am currently cd'd onto the server, and I am using nodemon and socket.io to try and connect to the server. So far I ran the command `npm run devStart' in the terminal, and when I do this it gives me these messages
[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js
The thing is the last message, "[nodemon] starting 'node server.js' is in green meaning that it is attempting to start the server, but it never does! It just stays like that.
In my server.js I have the following code
const io = require("socket.io")(3001, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("The connection has been established");
});
Therefore, when I run npm run devStart
I am expecting it to also console.log('The connection has been established')
beacuse that is how I will know the server connection has been made.
here is the package.json code relating to the devStart (scripts)
"scripts": {
"devStart": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
I tried to go online, but no one really explained this problem. I am a bit of a beginner to coding, so this might be a simple solution so as always any help would be massively appreciated!
If the intention is to have it so when the server starts you are prompted with a message to know the service is running this isn't the purpose of the io.on("connection")
event handler.
In your example, you're creating an httpServer instance inside of socket.io, which is published and accessible via the listening events of socket.io. So, you can do something like this:
const io = require("socket.io")(3001, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
// New: Listen for the listening event
io.httpServer.on("listening", () => {
console.log(`Server started on port 3001`);
});
io.on("connection", (socket) => {
console.log("The connection has been established");
});
When a client connects to your server, it will then be triggered in the io.on("connection") event. You can read more about the client api here in socket.io's official documentation