File
Blob: samples/filesystem/worker.js
| 1 | // Copyright (c) 2017-2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | import { Buffer } from 'node:buffer'; |
| 6 | |
| 7 | const root = await navigator.storage.getDirectory(); |
| 8 | const tmp = await root.getDirectoryHandle('tmp'); |
| 9 | export default { |
| 10 | async fetch(req, env) { |
| 11 | |
| 12 | // Any files that are created in the tmp file directory will be |
| 13 | // automatically cleaned up by the runtime after each request. |
| 14 | // The tmp dir is specific to each request, so concurrent requests |
| 15 | // will not interfere with each other and there is no shared state |
| 16 | // between requests. |
| 17 | |
| 18 | // Web File System APIs... |
| 19 | const file = await tmp.getFileHandle("foo", { create: true }); |
| 20 | const writable = await file.createWritable(); |
| 21 | await writable.write('Hello World\n'); |
| 22 | await writable.close(); |
| 23 | |
| 24 | // Node.js File System APIs... |
| 25 | const { readFileSync } = await import('node:fs'); |
| 26 | const data = readFileSync('/tmp/foo', 'utf8'); |
| 27 | |
| 28 | return new Response(data); |
| 29 | } |
| 30 | }; |