localStorage and sessionStorage — as global objects in every script. They work exactly as they do in the browser, with one important distinction: localStorage can persist its contents across separate ant invocations when you pass --localstorage-file <path>. This gives your scripts a simple key-value store that survives process restarts without adding any npm dependencies.
localStorage vs. sessionStorage
localStorage | sessionStorage | |
|---|---|---|
| Persistence | Survives process exit when --localstorage-file is set | Lost when the process exits |
| Scope | Shared across all scripts that use the same file | Scoped to the current process |
| API | Web Storage API | Web Storage API (identical) |
Without
--localstorage-file, localStorage behaves exactly like sessionStorage — it is in-memory only and discarded when the process exits.API reference
BothlocalStorage and sessionStorage implement the same interface.
Store
value under key. Both arguments must be strings. If key already exists, its value is overwritten.Retrieve the value stored under
key. Returns null if the key does not exist.Delete
key and its associated value. Has no effect if the key does not exist.Remove all key-value pairs from storage.
The number of key-value pairs currently in storage.
Return the key at position
index (zero-based). Returns null if index is out of range. The order of keys is not guaranteed to match insertion order.Persisting data across runs
Pass--localstorage-file <path> to point localStorage at a JSON file on disk. Ant reads the file at startup and writes it back on exit.
Example: a persistent visit counter
getItem returns null for missing keys, the || '0' fallback handles the first run cleanly without throwing.
Example: storing structured data
localStorage only stores strings. Serialize structured data with JSON.stringify and deserialize with JSON.parse.
Using sessionStorage
sessionStorage has the same API as localStorage but never persists to disk. Use it when you need a temporary scratch space that multiple functions can share within a single script run.