Skip to content

Commit 69eed90

Browse files
Filmbostock
andauthored
document data loaders' cwd and import.meta.url (#996)
* document data loaders' cwd and import.meta.url closes #853 * format code * Update loaders.md --------- Co-authored-by: Mike Bostock <[email protected]>
1 parent 9ca3b31 commit 69eed90

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

docs/loaders.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,15 @@ For example, for the file `quakes.csv`, the following data loaders are considere
150150

151151
If you use `.py`, `.R`, `.rs`, or `.go`, the corresponding interpreter (`python3`, `Rscript`, `rust-script`, or `go run`, respectively) must be installed and available on your `$PATH`. Any additional modules, packages, libraries, _etc._, must also be installed before you can use them.
152152

153+
Data loaders are run in the same working directory in which you run the `observable build` or `observable preview` command, which is typically the project root. In Node, you can access the current working directory by calling `process.cwd()`, and the data loader’s source location with [`import.meta.url`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta). To compute the path of a file relative to the data loader source (rather than relative to the current working directory), use [`import.meta.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve). For example, a data loader in `docs/summary.txt.js` could read the file `docs/table.txt` as:
154+
155+
```js run=false
156+
import {readFile} from "node:fs/promises";
157+
import {fileURLToPath} from "node:url";
158+
159+
const table = await readFile(fileURLToPath(import.meta.resolve("./table.txt")), "utf-8");
160+
```
161+
153162
Whereas `.js`, `.ts`, `.py`, `.R`, `.rs`, `.go`, and `.sh` data loaders are run via interpreters, `.exe` data loaders are run directly and must have the executable bit set. This is typically done via [`chmod`](https://en.wikipedia.org/wiki/Chmod). For example:
154163
155164
```sh

0 commit comments

Comments
 (0)