33

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

3 Answers 3

21

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked after renaming the file. But I'm in a very specific case where renaming the file is not a viable solution. Isn't there any way of declaring it as a module without renaming the file?
No. There isn't.
18

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

1 Comment

From my answer: The --input-type flag only applies to --eval'd or source STDIN files.
6

A different alternative without renaming the file is executing the code with a pipe in bash. The following command works fine as a module:

cat code.js | node --input-type=module

1 Comment

too bad there is an option like node --type=module ./code.js. would be cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.