Is there any way of executing ES syntax in a Node.js shell?

Viewed 41

Let's say I create a file called file.mjs with the following content:

import axios from 'axios' 

const response = await axios.get('https://nominatim.openstreetmap.org/reverse.php?lat=-23.513442&lon=-46.384794&zoom=18&format=jsonv2')
console.log(response.data)

Let's also say I execute this file with the command node file.mjs... Because of its mjs extension, I'm capable of executing this file as a module and so I can use await outside the async function. Also, I can use the import statement to declare my libraries.

So far everything works fine... But let's say I open a Node.js shell by executing the command node. I'll end up in a prompt like:

 user@computer  ~  node
Welcome to Node.js v16.14.2.
Type ".help" for more information.
> 

This prompt will not accept ES syntax inside it... That means I'll have to import libraries with the require function and I'll have to use async functions in order to use await. Is there any way of making a Node.js shell execute ES syntax? Just so I can execute the javascript from my sample exactly as it is?

1 Answers

You can use dynamic import, which is the import() function, in the REPL. Let's say you're in a folder that has a node_modules folder with axios installed. Then, you can simply open the REPL in there and do something like this:

const axios = (await import("axios")).default;

This is the only way to use import in a REPL, you cannot load your file.mjs exactly like that and would have to use dynamic import in your file.mjs instead.

Related