server.js
import express from 'express';
import { createReadStream } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
console.log("filename=", __filename);
const __dirname = dirname(__filename);
console.log("dirname =", __dirname);
const app = express();
const staticPath = join(__dirname, 'public');
console.log("Staticpath=", staticPath);
app.use(express.static(staticPath));
app.get('/', (req, res) => {
console.log("Staticpath.index.html=", join(staticPath, 'index.html'));
const stream = createReadStream(join(staticPath, 'index.html'));
stream.on('error', (err) => {
console.error(err);
res.status(500).send('Internal Server Error');
});
stream.pipe(res);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Terminal output of error
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
filename= /home/projects/stackblitz-starters-3ehyvi/server.js
dirname = /home/projects/stackblitz-starters-3ehyvi
Staticpath= /home/projects/stackblitz-starters-3ehyvi/public
Server listening on port 3000
Staticpath.index.html= /home/projects/stackblitz-starters-3ehyvi/public/index.html
[ENOENT: no such file or directory, open '/home/projects/stackblitz-starters-3ehyvi/public/index.html'] {
code: 'ENOENT',
errno: -2,
path: '/home/projects/stackblitz-starters-3ehyvi/public/index.html',
syscall: 'open'
}
project structure
FILES
public
index.html
.gitignore
package-lock.json
package.json
server.js
package.json
{
"name": "node-starter",
"private": true,
"type": "module",
"scripts": {
"dev": "nodemon server.js"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^3.0.3"
}
}
NOTE It finds it if the index.html is moved to the root where the server.js resides and staticPath = __dirname.
The path in the log seems correct but it still is unable to find it in the public folder.