-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
74 lines (65 loc) · 1.86 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import * as fs from "fs/promises"
import temp from "temp"
import { execFile } from "child_process"
import { promisify } from "util"
const execFileAsync = promisify(execFile)
export type ConfigOptions = {
format?: "midi" | "pdf" | "ps" | "png" | "svg" | "eps"
resolution?: number // In ppcm
binaryPath?: string
}
export const defaultOptions: ConfigOptions = {
format: "png",
resolution: 50,
binaryPath: "lilypond",
}
export async function render(lilypond: string, options: ConfigOptions) {
const tempPath = temp.path({ suffix: ".ly" })
await fs.writeFile(tempPath, lilypond, { encoding: "utf8" })
return await renderFile(tempPath, options)
}
export async function renderFile(
filePath: string, // Path to the .ly file
options: ConfigOptions = defaultOptions
) {
const optionsNorm = Object.assign({}, defaultOptions, options)
const formatMap = {
midi: "",
pdf: "--pdf",
png: "--png",
ps: "--ps",
svg: "--svg",
eps: "--eps",
}
const isSupportedFormat = Boolean(
optionsNorm.format &&
typeof formatMap[optionsNorm.format] !== "undefined" &&
formatMap[optionsNorm.format] !== null
)
if (!isSupportedFormat) {
throw new Error(optionsNorm.format + " is not a supported export format")
}
const tempName = temp.path()
const tempFile = tempName + "." + optionsNorm.format
const binaryPath = optionsNorm.binaryPath || "lilypond"
const result = await execFileAsync(
binaryPath,
[
optionsNorm.format ? formatMap[optionsNorm.format] || "" : "",
[
"--define-default",
"resolution=" + (optionsNorm.resolution || 1) * 2.54,
],
["--define-default", "no-point-and-click"],
"--silent",
["--output", tempName],
filePath,
].flat()
)
if (result.stderr) {
throw new Error(result.stderr)
} //
else {
return await fs.readFile(tempFile, {})
}
}