Initial Version
Create a package
Run the npm init
command to create a package.json file for your application.
npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them except the entry point.
We prefer to use app.js rather than index.js.
Its result should be similar to this:
package name: (lr_webchat_node)
version: (1.0.0)
description: Chat app back-end built in node.js.
entry point: (index.js) app.js
test command:
git repository: https://github.com/Literank/lr_webchat_node.git
keywords: socket.io,websocket
author: literank.com
license: (ISC) MIT
About to write to /Users/netdong/workspace/2023/projects/lr_webchat_node/package.json:
{
"name": "lr_webchat_node",
"version": "1.0.0",
"description": "Chat app back-end built in node.js.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Literank/lr_webchat_node.git"
},
"keywords": [
"socket.io",
"websocket"
],
"author": "literank.com",
"license": "MIT",
"bugs": {
"url": "https://github.com/Literank/lr_webchat_node/issues"
},
"homepage": "https://github.com/Literank/lr_webchat_node#readme"
}
This command creates a package.json
file in which dependencies you add will be listed for tracking.
Install Dependencies
Install Socket.IO:
npm i socket.io
This command updates the package.json
file and creates a package-lock.json
file in your project.
Module Type
Update package.json:
@@ -1,6 +1,7 @@
{
"name": "lr_webchat_node",
"version": "1.0.0",
+ "type": "module",
"description": "Chat app back-end built in node.js.",
"main": "app.js",
"scripts": {
In a package.json
file, "type": "module"
indicates that the project is using ECMAScript modules (ES modules) rather than CommonJS modules.
Integrating Socket.IO
Create app.js:
import { createServer } from "http";
import { Server } from "socket.io";
// Create a basic HTTP server
const server = createServer();
// Attach Socket.IO to the HTTP server with CORS enabled
const io = new Server(server, {
cors: {
origin: "*", // Access from any origin
},
});
// Handle incoming socket connections
io.on("connection", (socket) => {
console.log("A user connected", socket.id);
});
// Start the server
const PORT = process.env.PORT || 4000;
server.listen(PORT, () => {
console.log("Chat Server listening on port " + PORT);
});
Run the program like this:
node app.js
You will get one line like this:
Chat Server listening on port 4000
Your chat server is running on port 4000 now.