'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:
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. I'd like to accomplish that without creating a project with a package.json file. 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. I know there's a --input-type=module parameter I can use with it. But I've tried running node --input-type=module code.js and I've received the following error:
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)?
Solution 1:[1]
Rename the file to name.mjs. This --input-type parameter only applies to STDIN and --eval-d files.
Solution 2:[2]
This isn't really possible from the command line. You have only two options for making your file ESM.
Edit
package.jsonto have the following key and value.{ "type": "module" }Change the file extensions from
.jsto.mjs. The m stands for module.
In conclusion, the flag below doesn't help with changing the type to module.
$ node code.js --input-type=module
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 | 0xLogN |
| Solution 2 | Arnav Thorat |
