By 609varsha
In my project of node.js which is a ES module(as I have used “type”: “module” in package.JSON file) I am trying to render HTML file and image file which is stored in a “public” folder. When I am using app.use(express.static(‘public’)) and app.get(‘index.html’,{root:__dirname}). I am getting error
Error: __dirname is not defined
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi there,
In a Node.js project that uses ES modules (as indicated by "type": "module" in your package.json), traditional Node.js variables like __dirname and __filename are not available. This is because ES modules have a different scope and module resolution mechanism compared to CommonJS modules.
However, there’s a way to replicate the functionality of __dirname in an ES module environment. You can use import.meta.url to get the current module’s URL and then derive the directory name from it. Here’s how you can do it:
Import Required Modules: First, make sure to import the necessary modules. Since you are using Express, you need to import it. You also need to import path and url from Node.js to work with file paths.
Calculate __dirname Equivalent: Use import.meta.url with the url and path modules to determine the equivalent of __dirname.
Configure Express to Serve Static Files: Use the calculated path to serve your static files from the public directory.
Here’s a sample code snippet that demonstrates this:
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// Create a new express application
const app = express();
// Calculate the __dirname equivalent
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Serve static files from the 'public' directory
app.use(express.static(join(__dirname, 'public')));
// Define a route for 'index.html'
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'public', 'index.html'));
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this code:
fileURLToPath(import.meta.url) is used to get the file path of the current module (similar to __filename in CommonJS).dirname(__filename) gives you the directory name of the current module (similar to __dirname in CommonJS).express.static(join(__dirname, 'public')) is used to serve static files from the public directory.'/' is set up to serve your index.html.This setup should allow you to serve static files, including your HTML and image files, from the public directory in your Node.js ES module project.
Best,
Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.