How can I create a minimal NodeJS script. mjs? What's that?
TIL .mjs
is a thing, since when?
When running my script (e.g. node myscript.js
) I see the error "SyntaxError: Cannot use import statement outside a module
", why?
I write a lot of Python, and I'm used to (like in bash
) writing quick little scripts to perform a task, and runing them with python mything.py
. So I expected the same thing with node mything.js
would be possible with NodeJS.
I wanted to quickly parse some YAML in node
so I discored the YAML node package, followed it's README and wrote something like this:
import fs from 'fs'
import YAML from 'yaml'
YAML.parse('[ true, false, maybe, null ]\n')
// [ true, false, 'maybe', null ]
const file = fs.readFileSync('./file.yml', 'utf8')
console.log(YAML.parse(file))
But if you do that, and try to run with node mything.py
you'll see the error:
$ node test.js
(node:603976) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
mything.js:1
import fs from 'fs'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:128:18)
at wrapSafe (node:internal/modules/cjs/loader:1280:20)
at Module._compile (node:internal/modules/cjs/loader:1332:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
at Module.load (node:internal/modules/cjs/loader:1206:32)
at Module._load (node:internal/modules/cjs/loader:1022:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49
Node.js v20.12.0
Turns out you can, as the error message suggests, name your script with a .mjs
extention to make your intentions explicit. So mything.js
becomes mything.mjs
, and away we go! No error, and we have our handy script in NodeJS. No need to do any extra work.
$ # Our script now runs as expected
$ node test.mjs
{ snickers: 'GO_ON_THEN' }
See also
Releated links: