Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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

like image 201
raylight Avatar asked Sep 02 '25 04:09

raylight


2 Answers

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

like image 151
0xLogN Avatar answered Sep 05 '25 02:09

0xLogN


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.

# DOESN'T WORK LIKE THIS. SEE BELOW:
$ node code.js --input-type=module

# However, as pointed out in the other answers, you can:
$ cat code.js | node --input-type=module
like image 25
Viradex Avatar answered Sep 05 '25 00:09

Viradex