3
It is common for me to see online courses, articles and tutorials over the internet, Node.js codes that can import local JSON files into code to be manipulated, used, tested, etc... In these examples, they use Commonjs to import JSON, using the require()
. Something like (for example):
Folder structure:
|
\_ test.json
|
\_ index.js
Content of the JSON:
{
"foo": "baz"
}
Node.js code:
const json = require('./test.json');
// exibe: { foo: 'baz' }
console.log(json);
The problem is that this methodology does not work when using ESM (Ecmascript modules). The code below will return an error:
For those who don’t know, in recent versions of Node.js you can use ESM by configuring the package json. defining "type": "module"
.
import json from './test.json';
console.log(json);
Error:
node:internal/process/esm_loader:74
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/cmt-cardeal/<path-irrelevante>/test.json
at new NodeError (node:internal/errors:363:5)
....
}
If I try to interoperate Commonjs with ESM, ie use the require
within a file defined as ESM, I have another error in the terminal:
file:///home/cmt-cardeal/<path-irrelevante>/index.js:3
const json = require('./test.json');
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/cmt-cardeal/<path-irrelevante>/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
...
Explained this, I wanted to know:
- How to import JSON content into a file defined as ESM unused
FS
and without having to rename the file to the extension.cjs
?
My version of Node.js when preparing this question: v16.0.0
Recalling: Javascript: Differences between import and require
LEIA-ME
: If you find that this question is duplicated, please feel free to signal, because I found nothing similar. :)– Cmte Cardeal
DICA
: If anyone wants to propose an answer, the tip is to use thecreateRequire
of core modulemodule
. I am trying to contribute questions with relevant information to help the community and if no one has an answer, in the future I put my answer. :)– Cmte Cardeal
I would question that part: "without using FS". Why?
– Luiz Felipe
@Luizfelipe commented in his reply
– Cmte Cardeal