node.jsexpressimportrequireexpress-router

How can I use require and import both in node.js?


This is my server.js file:

const express = require('express');
const connectDB = require('./config/db');
const path = require('path');

const app = express();

// Connect Database
connectDB();

// Init Middleware
app.use(express.json());

// Define Routes
app.use('/api/users', require('./routes/api/users'));

In this code, I have some problem like following.

node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_REQUIRE_ESM]: require() of ES Module E:\Study\DEC\devconnector_mobang\config\db.js from E:\Study\DEC\devconnector_mobang\index.js not supported.
Instead change the require of db.js in E:\Study\DEC\devconnector_mobang\index.js to a dynamic import() which is available in all CommonJS modules.

This error 's reason is just require. So I hope to use both import and require or convert require into import. I have strived the some way.

import express from "express";
import connectDB from "./config/db.js";
import path from "path";

// Define require
import { createRequire } from "module";
const require = createRequire(import.meta.url);

const app = express();

// Connect Database
connectDB();

// Init Middleware
app.use(express.json());

const user = require("./config/default");

app.use("/api/users", user);

In here, it can't read this.

import connectDB from "./config/db.js";

But it can read this.

import connectDB from "./config/default.json";

I hope to help you for me to this problem. Thanks.

I hope to solve this problem


Solution

  • I have this problem solved. This problem is depended node version. Node 16 and Node 20 is definitely different. My node used version 20. I change it version 16 using nvm. Npm install is success and require is normal. Thanks