socketio / socket.io-website

Socket.IO website and blog
https://socket.io
318 stars 668 forks source link

Fix: Incorrect path resolution in ES module example #420

Closed Harshita-Naik16 closed 9 months ago

Harshita-Naik16 commented 10 months ago

Issue: The provided code example in the documentation for ES modules has an issue in the path resolution for serving the 'index.html' file.

Error shown in web browser:

Error: ENOENT: no such file or directory, stat 'D:\D:\dev\learning%20projects\socket\index.html'

Description: The code snippet for creating an Express server using ES modules, as provided in the documentation, uses an incorrect approach for resolving the path to the 'index.html' file. The usage of new URL('./index.html', import.meta.url).pathname is not effective for obtaining the correct file path.

Expected Behavior: The code example should correctly serve the 'index.html' file by resolving its path using ES6 module syntax.

Solution: An accurate method for resolving the file path involves using fileURLToPath(import.meta.url) from the 'url' module to obtain the file path and then correctly joining it with the 'index.html' file name using path.join().

Example Fix:

import express from 'express';
import { createServer } from 'http';
import { fileURLToPath } from 'url';
import path from 'path';

const app = express();
const server = createServer(app);

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.get('/', (req, res) => {
  const indexPath = path.join(__dirname, 'index.html');
  res.sendFile(indexPath);
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

How to test?

  1. Home page of socket.io
  2. Click on Get Started
  3. step 2 Serving HTML under Es modules
darrachequesne commented 9 months ago

Good catch! This should be fixed now.