[英]Is it possible to run a node.js script as a module with the node command (without using package.json)?
Let's say I have a code.js
file with the following node.js script:假设我有一个包含以下 node.js 脚本的
code.js
文件:
const axios = require('axios')
async function getData(){
const response = await axios.get('https://mypage.com.br')
console.log(response.data)
}
getData()
If I execute it with node code.js
it works perfectly fine... However, I'd like to execute it as a module, just so I can use the import
statement and use the await
command as top level.如果我使用
node code.js
执行它,它工作得很好......但是,我想将它作为一个模块执行,这样我就可以使用import
语句并将await
命令用作顶层。 I'd like to accomplish that without creating a project with a package.json
file.我想在不使用
package.json
文件创建项目的情况下完成此操作。 My final result would be something like this:我的最终结果是这样的:
import axios from 'axios'
const response = await axios.get('https://mypage.com.br')
console.log(response.data)
I haven't managed to make it work with the node
command.我还没有设法让它与
node
命令一起工作。 I know there's a --input-type=module
parameter I can use with it.我知道我可以使用一个
--input-type=module
参数。 But I've tried running node --input-type=module code.js
and I've received the following error:但是我尝试运行
node --input-type=module code.js
并且收到以下错误:
SyntaxError: Cannot use import statement outside a module
So, that means it's not even being recognized as a module yet.所以,这意味着它甚至还没有被识别为一个模块。 Is it possible to do?
有可能吗? Can I execute an isolated script with the command
node
as a module (while using await
on top level)?我可以将命令
node
作为模块执行一个独立的脚本吗(在顶层使用await
时)?
Rename the file to name.mjs
.将文件重命名为
name.mjs
。 This --input-type
parameter only applies to STDIN and --eval
-d files.此
--input-type
参数仅适用于 STDIN 和--eval
-d 文件。
This isn't really possible from the command line.这在命令行中是不可能的。 You have only two options for making your file ESM.
您只有两个选项来制作文件 ESM。
Edit package.json
to have the following key and value.编辑
package.json
以具有以下键和值。
{ "type": "module" }
Change the file extensions from .js
to .mjs
.将文件扩展名从
.js
更改为.mjs
。 The m stands for module . m代表模块。
In conclusion, the flag below doesn't help with changing the type to module.总之,下面的标志无助于将类型更改为模块。
$ node code.js --input-type=module
A different alternative without renaming the file is executing the code with a pipe
.另一种不重命名文件的替代方法是使用
pipe
执行代码。 The following command works fine as a module:以下命令作为模块运行良好:
cat code.js | node --input-type=module
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.