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

Tips on retrieving the UserId from the localStorage

Building a blog is my current project. At a certain point, I need to display all the blogs created by a specific user only. To achieve this, I have saved the user information in Local Storage and now I am trying to retrieve the username so that I can send ...

NuxtJS (Vue) loop displaying inaccurate information

I have a dataset that includes multiple languages and their corresponding pages. export const myData = [ { id: 1, lang: "it", items: [ { id: 1, title: "IT Page1", }, { ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

The issue arising from utilizing the export class function in Angular 8

Hey there! I'm working on an Angular application and just getting started with it. My current version is Angular 8, and I've encountered an issue that I need help with. In my project, I have a shared model named "Client" which is defined in a fi ...

Utilizing Nodemailer and ReadableStreams to send email attachments stored in S3

My current challenge involves sending emails with Nodemailer that include attachments hosted in S3, utilizing JS AWS SDK v3. The example provided in the Nodemailer documentation demonstrates how to send an attachment using a read stream created from a file ...

Utilizing the power of AngularJS, NodeJS, and Mongoose to create dynamic and

I am relatively new to the world of JavaScript. I am currently experimenting with using pie charts from Highcharts (www.highcharts.com) in conjunction with AngularJS. In the example provided below, everything works smoothly, except for the fact that the "i ...

What are the limitations of using concatMap for handling multiple requests simultaneously?

In my current function, I am receiving an array of objects called data/ids as a parameter. Within this function, I need to execute a post request for each element/id: fillProfile(users) { const requests = []; console.log( 'USERS.length:&apos ...

Error encountered while testing karma: subscription function is not recognized

I encountered an issue with my karma unit test failing with the following error message. "this.gridApi.getScaleWidth().subscribe is not a function" GridApi.ts export class GridApi { private scaleWidthSubject = new BehaviorSubject<{value: number}& ...

Exploring the concept of nested routing in Node.js using Express

I'm having trouble setting up a nested route in my Express application. Here's what I have: app.put('api/template/:id/page/:pageID', updateTemplatePage); However, when I make the call from my page, I keep getting a 404 error. Here&apo ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

Retrieve the value of an express session on a different page in a NodeJS application

I'm facing an issue with setting a session value on app.get('/login', ()) and then not being able to retrieve that value on any other page besides the login page. I'm wondering if this is the expected behavior of express-session or if ...

What happens if the .env file is not stored in git when deploying to EC2? How does the production code access the necessary variables in this scenario?

If .env is in the gitignore file, how does the production code access the necessary values? I believe Jenkins manages this to ensure security, but I would appreciate it if someone could explain how this process works. My knowledge of DevOps is limited. ...

Comparing Server Sent Events and Ajax with Websockets and Ajax

I am currently developing an application using Nuxt.js and facing challenges in determining the best approach for sending data to the API built with Express.js and receiving real-time updates. I have identified that "bi-di" connections can be established u ...

Why does TypeScript not recognize deconstructed arrays as potentially undefined variables?

When looking at the code snippet below, I was under the impression that the destructured array variables, firstName and lastName, would be classified as string | undefined. This is because the array being destructured could have fewer variables compared ...

Obtain characteristics of the primary element in Ionic version 2 or 3

After creating and opening my Sqlite database and saving the SQLiteObject in a variable within my app.component.ts, I now need to retrieve these attributes in my custom ORM. The ORM extends to other providers to describe the title and field of my tables. ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

Outputting a JS file per component using Rollup and Typescript

Currently, I am in the process of developing a component library using React, TypeScript, and Rollup. Although bundling all components into a single output file index.js is functioning smoothly, I am facing an issue where individual components do not have ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

The server is unreachable due to a connection error

I encountered a server error with code ECONNREFUSED. While my API functions perfectly on my local machine, I face connection issues when trying to host the code. If you directly access the URL, you will find products at . Here is the API URL used to acces ...