There are 3 new helpful features in Node.js v18+ that make it easy to write simple scripts that make API requests without running npm install or a build step, and even without running npm init. fetch is stable as of Node.js v21, while --watch and --test are still experimental.
- fetch
- --watch
- --test
- .mjs
- nvm
fetch
fetch can stand in for axios if we want a zero-dependency script.
See Using the Fetch API - Web APIs | MDN.
fetch(url).then(response => response.text());
We can use btoa to pass Basic authorization:
const url = "http://"
const user = "username";
const pass = "password";
const authString = 'Basic' + btoa(`${user}:${pass}`)
fetch(url, { headers: { Authorization: authString } } })
--watch
Calling node --watch [filename]
will re-run your script every time you make a change, similar to how webpack-dev-server or the old browser-sync package will reload your web app on file changes.
By default, it watches the entrypoint (specificed in package.json) and anything imported or required. You can customize what’s watched with --watch-path=/path/to/watch
.
--test
Calling node --test *.test.*js
allows you to write tests with node:test
and node:assert
, as a stand-in for Cypress, Jest, or Mocha.
See details about comparing with node:assert.
.mjs
If you want to jump in without running npm init or configuring a package.json, using the .mjs file extension allows you to export ES modules. Otherwise, you’ll need to set type: module
in package.json if you’re exporting and importing within your script(s).
You’ll typically need to do one or the other when using --test
since the .test.*js file will import your script.
nvm
If you’ve followed the recommendation to use nvm to manage your version of node, you can easily switch to the latest version of Node.js and the latest behavior of fetch, --watch and --test by running nvm install node
. You may consider creating a .nvmrc
file for your project (link) and configuring your shell to automatically switch node versions (link).