-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-document.js
60 lines (52 loc) · 1.46 KB
/
create-document.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
const {
Document,
Packer,
Paragraph,
TextRun,
} = require('docx');
const { readFile, writeFile } = require('fs/promises');
const { normalizePath } = require('./utilities');
/**
* Create a DOCX document
* @param {string[]} paths - paths to the files that should be included in the document
* @param {string} initialPath - initial provided path
* @returns {Promise<void | Error>}
*/
const createDocument = async (paths = [], initialPath = '') => {
try {
const paragraphs = [];
const normalizedInitialPath = normalizePath(initialPath);
const [root] = normalizedInitialPath.split('/').slice(-1);
/* eslint-disable-next-line */
for await (let path of paths) {
const fileData = await readFile(path, { encoding: 'utf8' });
const pathText = `~/${path.substring(path.indexOf(root), path.length)}`;
paragraphs.push(new Paragraph({
children: [
new TextRun({
bold: true,
size: 14,
text: `// ${pathText}`,
}),
new TextRun({
break: 2,
size: 12,
text: fileData,
}),
],
}));
}
const document = new Document({
sections: [{
children: [
...paragraphs,
],
}],
});
const string = await Packer.toBuffer(document);
return writeFile(`${process.cwd()}/Result.docx`, string);
} catch (error) {
throw new Error(error);
}
};
module.exports = createDocument;