[英]Is there any way to use require and import in node
I have two differents files in a node project, in one of them, I have to use a json file to extract an array, I was using require.我在一个节点项目中有两个不同的文件,在其中一个文件中,我必须使用 json 文件来提取数组,我使用的是 require。 In the other one, I have to import some features from a module.在另一个中,我必须从模块中导入一些功能。 The problem is, importing is not working if I don't have问题是,如果我没有,导入将不起作用
"type" : "module"
In my package.json, but doing this, require is not working.在我的 package.json 中,但是这样做,require 不起作用。 I tried to change require for import with the json file, but to execute, I have to use我试图用 json 文件更改导入的 require,但要执行,我必须使用
node --experimental-json-modules file.js
And we are suppose not to use that flag when running.我们假设在运行时不使用该标志。
You should pick require()
or import
- not both.您应该选择require()
或import
- 不能同时选择。 When in an ESM module (where you can use import
), require()
is not defined.在 ESM 模块中(您可以在其中使用import
), require()
未定义。 If you want to use import
for loading modules, then set up the "type": "module"
properly and use import
.如果要使用import
加载模块,请正确设置"type": "module"
并使用import
。 Then, to load a JSON file, all it takes is a little function:然后,要加载一个 JSON 文件,只需要一个小函数:
async function loadJSON(file) {
let data = await fs.promises.readFile(file);
return JSON.parse(data);
}
Or, if you want to do it synchronously:或者,如果您想同步进行:
function loadJSONSync(file) {
let data = fs.readFileSync(file);
return JSON.parse(data);
}
Which you can put into a shared module itself so you can use it anywhere you want.您可以将其放入共享模块本身,以便您可以在任何地方使用它。 Note that in both of these functions, you will need to catch errors.请注意,在这两个函数中,您都需要捕获错误。 With the asynchronous option, it returns a promise and you need to check for both success and rejection.使用异步选项,它返回一个承诺,您需要检查成功和拒绝。 For the synchronous version, you need to catch any exceptions it might throw.对于同步版本,您需要捕获它可能抛出的任何异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.