'Issue With Trying to Import a Local File in Node v14.15.1

I am trying to import a local file from my project's directory to my server.js. The directory structure is like this:

server
  node_modules
  server.js (error occurs here) 
  src
    models
    api
       controllers
       routes
         posts.js (trying to import this file, edited to show actual filename)

Here's the error it throws

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

 Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\ReactProjects\memoirs\server\src\api\routes\posts' 
 imported from E:\ReactProjects\memoirs\server\server.js
 Did you mean to import ../src/api/routes/posts.js?
  at finalizeResolution (internal/modules/esm/resolve.js:276:11)
  at moduleResolve (internal/modules/esm/resolve.js:699:10)
  at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
  at Loader.resolve (internal/modules/esm/loader.js:85:40)
  at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)
  at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:51:40)
  at link (internal/modules/esm/module_job.js:50:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
[nodemon] app crashed - waiting for file changes before starting...

and my server.js file:

import express from 'express';
import posts from './src/api/routes/posts'; // is there a problem with this file path?

const app = express();

app.use('/api/v1/posts', posts); // error seems to be here, server works if commented out

app.listen(3004, (err)=>{
if(err){
    console.log(err);
}
console.log('server at port 3004');
});

The issue seems to be with the file path. I have tried re-arranging it but for some weird reason can't load that particular file into server.js Is there any clear explanation for why this is happening and how to rectify it? Thanks.



Solution 1:[1]

It seems like you made a typo. You wrote posts instead of post.

import post from './src/api/routes/post';

EDIT: Seeing that this was just a typo in the question, here is something you could try t fix it:

I would rely on CommonJS Require rather than ES6 Imports on this one, because you can specify relative paths easily by utilizing __dirname:

let express = require('express');
let posts = require(__dirname + '/src/api/routes/posts.js');

Solution 2:[2]

I've finally solved this! I got clue from react which throws exact error on not writing .js while importing. You must write extension of even a .js file for node 14+ if you are using type: 'module' in package.json.

Check this image Check this image

Solution

  • So the solution is edit the second line of server.js, from
  • import posts from './src/api/routes/posts' to
  • import posts from './src/api/routes/posts.js'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2