-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (88 loc) · 2.42 KB
/
index.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const chokidar = require("chokidar");
const path = require("path");
const childProcess = require("child_process");
const fs = require("fs");
const spawn = childProcess.spawn;
const exec = childProcess.exec;
const args = process.argv.slice(2);
const build = () => {
console.log("This script has not been implemented yet.");
};
const watch = () => {
/**
* File watcher
*/
const watcher = chokidar.watch("./markdown/**/*.md", {
ignored: [
/(^|[\/\\])\../, // ignore dotfiles
"node_modules",
],
persistent: true,
});
/**
* Start listening for file changes
*/
watcher
.on("change", (path) => compileMarkdownToPdf(path))
.on("error", (error) => console.log(`Watcher error: ${error}`))
.on("ready", () =>
console.log(
"Watcher active! Will auto-compile when changes are detected in the ./markdown directory."
)
);
};
/**
* Create a folder path if it does not already exist
*/
const createFolderIfNotExists = (path) => {
fs.mkdir(path, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
};
/**
* Compile file from .md to .pdf
*/
const compileMarkdownToPdf = (changed) => {
const inputDir = path.parse(changed).dir;
const inputFile = path.parse(changed).name;
const saveDir = inputDir.replace("markdown", "pdf");
const savePath = path.join(saveDir, `${inputFile}.pdf`);
createFolderIfNotExists(saveDir);
runPandoc(changed, savePath);
};
/**
* Run pandoc exec to do the actual compiling
*/
const runPandoc = (inputPath, outputPath) => {
console.log(`Starting compiling of ${inputPath} into ${outputPath} ...`);
exec("where pandoc", (err, stdout) => {
if (err || !stdout) {
throw err || new Error("Cant find pandoc. Make sure its installed");
}
let pandocPath = stdout.substr(0, stdout.length - 1);
let pandoc = exec(
`"${pandocPath}" ${inputPath} -o ${outputPath} --citeproc --pdf-engine=xelatex`,
(err, stdout) => {
if (err) {
throw err;
}
console.log("Conversion complete!");
}
);
});
};
/**
* Handle arg input
*/
switch (args[0]) {
case "build":
build();
break;
case "watch":
watch();
break;
default:
break;
}