MenuGuides / Test code that reads files or calls an API

Docs / Guides

Test code that reads files or calls an API

A Node Snippet runs on real Node, with your own access to files, the network and other programs.

On this page

JSpark does not confine a Node Run. Code that deletes a file deletes it, and code that sends a request sends it. So when a Snippet can reach outside JSpark, it runs only when you press Run.

Read a file

  1. Open the Node.js Starter, and replace its code with code that uses files.
  2. Look at the rail. The Run as you type button is replaced by a warning shield. Hover it to read why: Uses your files, so auto-run is paused.
  3. Press Run, or ⌘↵ or Ctrl+Enter.
The Snippet waits under the warning shield until Run is pressed, then prints what it read back.

A relative path, such as order.json, lands in the Working Folder. To see the file, choose Run → Reveal Working Folder. See The Working Folder.

Call an API

fetch, node:http and the other network modules count as the network. The shield then says Uses the network, so auto-run is paused. Press Run to send the request.

A server started by the Snippet answers its own request, and keeps listening until Stop.

A Snippet that starts a server keeps running while it waits for requests. Press Stop, or ⌘. or Ctrl+., to end it. The time limit stops only code that stays busy without a pause: see Time and memory limits.

Why it waits for you to press Run

Run as you type runs your code a moment after you stop typing, so it runs half-written code again and again. For code that writes files or sends requests, that could do something you did not mean, before you finish the line. So JSpark takes such a Snippet out of Run as you type. Nothing is blocked: you decide when it runs.

JSpark treats these as reaching outside:

  • Your files: fs, fs/promises
  • The network: fetch, http, https, net, WebSocket
  • Other programs: child_process, worker_threads, process.exit()
  • An npm package, unless JSpark knows it only computes (such as lodash or date-fns)
  • Code it cannot read before it runs: eval, or an import path built at run time

This check reads your code; it is not a sandbox. Code can reach outside in ways the check does not see, and then it runs as you type like any other Snippet. See Outside Access.

The pictures show JSpark on a Mac. On Windows, the window looks a little different and uses Ctrl for ⌘, but everything works the same way.

Esc

Type to search every docs page.