Skill Tracer
Skills › HyperFrames › media-use › audio-meta.mjs

audio-meta.mjs

39 lines · skills/media-use/audio/scripts/lib/audio-meta.mjs at a595755

1import { closeSync, ftruncateSync, openSync, readFileSync, writeSync } from "node:fs";
2
3// Keep the merge base and output on the same file even if its pathname changes
4// while audio generation runs. The CLI owns this handle until write or exit.
5export function openAudioMeta(path) {
6 let fd;
7 try {
8 fd = openSync(path, "r+");
9 } catch (error) {
10 if (error.code !== "ENOENT") throw error;
11 }
12 let value = {};
13 if (fd !== undefined) {
14 try {
15 value = JSON.parse(readFileSync(fd, "utf8"));
16 } catch (error) {
17 closeSync(fd);
18 throw error;
19 }
20 }
21 return {
22 value,
23 write(meta) {
24 const bytes = Buffer.from(JSON.stringify(meta, null, 2));
25 // Defer new-file creation until generation succeeds. Never overwrite a
26 // file (or follow a link) that appeared since the missing merge base.
27 if (fd === undefined) fd = openSync(path, "wx");
28 try {
29 let offset = 0;
30 while (offset < bytes.length) {
31 offset += writeSync(fd, bytes, offset, bytes.length - offset, offset);
32 }
33 ftruncateSync(fd, bytes.length);
34 } finally {
35 closeSync(fd);
36 }
37 },
38 };