Home > OS >  Is it possible to run a node.js script as a module with the node command (without using package.json
Is it possible to run a node.js script as a module with the node command (without using package.json

Time:04-11

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)?

CodePudding user response:

Rename the file to name.mjs. This --input-type parameter only applies to STDIN and --eval-d files.

CodePudding user response:

This isn't really possible from the command line. You have only two options for making your file ESM.

  1. Edit package.json to have the following key and value.

    {
      "type": "module"
    }
    
  2. Change the file extensions from .js to .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
  • Related