Report this

What is the reason for this report?

How to render statis file in nodejs if modules a re of type ES

Posted on October 26, 2021

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!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

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:

  1. 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.

  2. Calculate __dirname Equivalent: Use import.meta.url with the url and path modules to determine the equivalent of __dirname.

  3. 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.
  • The route for '/' 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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.