Error [ERR_MODULE_NOT_FOUND]: Unable to locate the specified module (TypeScript/TypeOrm)

I'm encountering an issue where the content of my database is not being printed when using an entity with TypeScript/TypeOrm. Here's the code I have:

Main file :

import { createConnection, getManager ,getConnectionOptions } from 'typeorm';
//import {ReleaseController} from "./controller/ReleaseController.js";
//import { attachControllers } from '@decorators/express';
import express from "express";
import { createExpressServer } from 'routing-controllers';
import "reflect-metadata";

import { Release } from "./entity/Release";

const connectionOptions = await getConnectionOptions();

console.log(connectionOptions)

await createConnection(connectionOptions).then(async connection => {

  const entityManager = getManager();   
  let releases        = await entityManager.find(Release);

  console.log("All releases from the db: ", releases);

}).catch(error => console.log(error));

const app = createExpressServer({
  //controllers: [ReleaseController], // we specify controllers we want to use
});

app.listen(3000);

Entity Release :

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Release {

    @PrimaryGeneratedColumn()
    release_id: number;

    @Column({ type: 'date' })
    date: string;

    @Column()
    name: string;

}

TS config :

  {
    "compilerOptions": {
        "module": "esnext",
        "moduleResolution": "node",
        "target": "esnext",
         
        "esModuleInterop": true,
        "noImplicitAny": true,
        "sourceMap": false,
        "allowJs": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "baseUrl": ".",
            "paths": {
                "*": ["node_modules/*"]
            }
    },
    "include": [ "src/**/*"],
    "logging": true,
    "logger": "file",
}

Output Error :

 node --trace-warnings .

node:internal/process/esm_loader:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/jp/eclipse-workspace/SingleCellSignal/src/entity/Release' imported from /home/jp/eclipse-workspace/SingleCellSignal/src/singlecellsignal.js
    at new NodeError (node:internal/errors:363:5)
    at finalizeResolution (node:internal/modules/esm/resolve:307:11)
    at moduleResolve (node:internal/modules/esm/resolve:742:10)
    at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:853:11)
    at Loader.resolve (node:internal/modules/esm/loader:89:40)
    at Loader.getModuleJob (node:internal/modules/esm/loader:242:28)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:73:40)
    at link (node:internal/modules/esm/module_job:72:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Answer №1

I am feeling completely disoriented and uncertain.

An error message pops up while trying to execute a specific node command.

(node:38717) UnhandledPromiseRejectionWarning: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/jp/eclipse-workspace/SingleCellSignal/dist/entity/Release.js
require() of ES modules is not supported.
require() of /home/jp/eclipse-workspace/SingleCellSignal/dist/entity/Release.js from /home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename Release.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/jp/eclipse-workspace/SingleCellSignal/package.json.

    at new NodeError (node:internal/errors:363:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1126:13)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at /home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:39
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories (/home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:10)
    at ConnectionMetadataBuilder.buildEntityMetadatas (/home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/connection/ConnectionMetadataBuilder.js:51:160)
    at emitUnhandledRejectionWarning (node:internal/process/promises:190:15)
    at processPromiseRejections (node:internal/process/promises:238:9)
    at processTicksAndRejections (node:internal/process/task_queues:97:32)
(node:38717) Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: 
/...omitted for brevity...</p>
    </div></answer1>
<exanswer1><div class="answer" i="67972431" l="4.0" c="1623671207" a="WmhlRnJlbmNo" ai="602268">
<p>I'm really struggling to comprehend this situation.</p>
<blockquote>
<p>node --trace-warnings --unhandled-rejections=warn --experimental-json-modules  --experimental-modules  --es-module-specifier-resolution=node ./dist/singlecellsignal.js</p>
</blockquote>
<pre><code>(node:38717) UnhandledPromiseRejectionWarning: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/jp/eclipse-workspace/SingleCellSignal/dist/entity/Release.js
require() of ES modules is not supported.
require() of /home/jp/eclipse-workspace/SingleCellSignal/dist/entity/Release.js from /home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename Release.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/jp/eclipse-workspace/SingleCellSignal/package.json.

    at new NodeError (node:internal/errors:363:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1126:13)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at /home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:39
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories (/home/jp/eclipse-workspace/SingleCellSignal/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:10)
    at ConnectionMetadataBuilder.buildEntityMetadatas (/home/jp/eclipse-workspace/SingleCellS

ignal/node_modules/typeorm/connection/ConnectionMetadataBuilder.js:51:160)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the solution to fixing the Vetur/Vuelidate issue where the error message "'validate' does not exist in type 'ComponentOptions<Vue [etc.]" is displayed?

QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...

Displaying logs based on the process.env.NODE_ENV condition

When running my ExpressJS app, I want to display logs only when the environment is set to dev. To specify the environment in package.json: set NODE_ENV=dev & node index.js My condition for displaying logs: server.app.use(function(request, response, n ...

"Sharing the entire contents of a table with Jade through node.js: A step-by-step guide

Is there a way to transfer all rows from the original console output to Jade using node.js? Currently, only one row of the WCF service is being sent to Jade. var response = result['s:Envelope']['s:Body'] [0].OrderReportResponse[0].exe ...

What is the best way to patiently wait for a promise to fulfill, retrieve its value, and pass it to another function?

I am facing an issue with getting the value of stringReply into my app.post method in Express. From what I understand, it seems like the code is fully executed before the promise is resolved, resulting in an undefined value when attempting to log stringR ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...

Exploring the magic of listening to a Unix socket in Sails.js

Listening to a Unix socket file in Express MVC is relatively straightforward and well-documented. However, when it comes to Sails.js, the process is not as clear due to the limited availability of documentation on this specific topic. ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

Leveraging HTTPOnly Cookie for GET request (Accessing user information from server with user_id cookie)

While I was learning from a tutorial, I encountered an interesting scenario where a user id is stored in an HTTPOnly cookie sent by the backend to the frontend after the user logs in. The challenge, however, is that HTTPOnly cookies cannot be accessed by t ...

Developing mongoose models using TypeScript for subdocuments

Exploring the integration of mongoose models with typescript, following a guide available at: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models. Unsure how arrays of subdocuments align with this setup. For instance, consider the model ...

Cannot send response headers once they have already been sent to the client [NEXTJS]

Currently, I am engrossed in a personal project focused on creating a dashboard using NextJS. This project serves as an opportunity for me to delve into learning NextJS and the fundamental concepts of TypeScript. My primary challenge at the moment revolves ...

Modify the size of images retrieved from the Twitch API

I have a request to the Twitch API to retrieve a list of top games and show their box art, but I'm facing an issue where the image will only display if I adjust the width and height values in the provided link. Is there a way to modify these values wi ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...

Steps to activate a button once the input field has been completed

It's noticeable that the send offer button is currently disabled, I am looking to enable it only when both input fields are filled. Below, I have shared my code base with you. Please review the code and make necessary modifications on stackblitz 1. ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

The Node and Express server are up and running in the terminal, however, when trying to connect to localhost on the web browser, an error message pops up saying "

Check out my awesome Node.js code: // Embracing ES6 syntax without worries, thanks to Babel for transpilation. import express from 'express'; // Initialize Express application. const app = express(); // Designate server port number. const PORT = ...

Retrieving information from the database and transferring it to the front end via the router

I have been working on a MERN Expo app login and sign-in page. However, I am facing an issue with fetching data from the backend after clicking the sign-in button. Even though I have implemented the find query in the Express router, I am unable to retrieve ...

How can I retrieve 5 random records from Mongoose that meet 5 distinct conditions?

This is a simplified version of my question model, focusing only on relevant data: exports = module.exports = function(app, mongoose) { var questionSchema = new mongoose.Schema({ difficultyLevel: { type: String, enum: ['easy&apo ...

Tips for retrieving the return value from a function with an error handling callback

I am having an issue with my function that is supposed to return data or throw an error from a JSON web token custom function. The problem I am facing is that the data returned from the signer part of the function is not being assigned to the token const a ...