4brains-node-generator
Version:
A CLI tool to generate a Node.js app by 4Brains Technologies
101 lines (84 loc) • 2.65 kB
JavaScript
import fs from "fs";
import path from "path";
import readline from "readline";
import { execSync } from "child_process";
import chalk from "chalk";
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function addSocketIo(ipAddresses) {
const projectRoot = process.cwd();
const indexPath = path.join(projectRoot, "index.js");
const socketIoImport = `import { Server } from "socket.io";\n`;
const httpImport = `import http from "http";\n`;
const ipArray = ipAddresses.split(",").map((ip) => ip.trim());
const corsOrigins = ipArray.map((ip) => `"http://${ip}"`).join(", ");
const socketIoSetup = `
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: [${corsOrigins}],
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
console.log("A user connected");
socket.on("disconnect", () => {
console.log("User disconnected");
});
});
// Middleware to pass io instance to routes
app.use((req, res, next) => {
req.io = io;
next();
});
`;
let indexContent = fs.readFileSync(indexPath, "utf8");
// Add imports if they don't already exist
if (!indexContent.includes(socketIoImport)) {
indexContent = socketIoImport + indexContent;
}
if (!indexContent.includes(httpImport)) {
indexContent = httpImport + indexContent;
}
// Ensure Socket.io setup is placed before routes
const routesStart = indexContent.indexOf("app.use(");
if (routesStart !== -1) {
indexContent =
indexContent.slice(0, routesStart) +
socketIoSetup +
indexContent.slice(routesStart);
} else {
indexContent += socketIoSetup;
}
// Replace existing app.listen if it exists
indexContent = indexContent.replace(/app\.listen\(port,.*\);/s, "");
// Append server.listen at the end if not already present
if (!indexContent.includes("server.listen(port")) {
indexContent += `
server.listen(port, () => {
const localIp = getLocalNetworkIp();
console.log(\`App is running on http://localhost:\${port}\`);
if (localIp) {
console.log(
\`App is also accessible on your local network at http://\${localIp}:\${port}\`
);
}
});
`;
}
fs.writeFileSync(indexPath, indexContent, "utf8");
// Install socket.io
console.log(chalk.green("Installing socket.io..."));
execSync("npm install socket.io", { stdio: "inherit" });
console.log(chalk.green("Socket.io integration added successfully."));
}
rl.question(
chalk.yellow("Enter the IP addresses for socket.io (comma-separated): "),
(ipAddresses) => {
addSocketIo(ipAddresses);
rl.close();
}
);