-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdocxFile.js
101 lines (78 loc) · 2.61 KB
/
docxFile.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
// docx file utilities when testing docx internal files
const os = require('os')
const path = require('path')
const fs = require('fs')
const extractZip = require('extract-zip')
const ZFolder = require('zfolder')
const format = require('xml-formatter')
const desktopPath = path.join(os.homedir(), 'Desktop')
async function main () {
try {
const args = process.argv.slice(2)
const command = args[0]
if (command === 'extract') {
await extract(args[1])
} else if (command === 'create') {
await create(args[1])
} else {
throw new Error(`Unknown command "${command}"`)
}
} catch (e) {
console.error('Error while executing')
console.error(e)
}
}
async function extract (docxPathArg) {
if (!docxPathArg) {
throw new Error('docxPath can not be empty')
}
if (!docxPathArg.endsWith('.docx')) {
throw new Error('docxPath does not have .docx extension')
}
const docxPath = path.resolve(desktopPath, docxPathArg)
const docxFilename = path.basename(docxPath, '.docx')
const outputPath = path.join(desktopPath, docxFilename)
await extractZip(docxPath, { dir: outputPath })
const xmlFiles = await getXMLFilesContent(outputPath)
for (const { fullPath, content } of xmlFiles) {
const xmlFormatted = format(content, {
indentation: ' ',
collapseContent: true,
lineSeparator: '\n'
})
await fs.promises.writeFile(fullPath, xmlFormatted)
}
console.log(`extracted into ${outputPath}`)
}
async function create (inputFolder) {
const inputFolderPath = path.resolve(desktopPath, inputFolder)
const outputPath = path.join(desktopPath, `${path.basename(inputFolderPath)}-new.zip`)
const finalDocxPath = path.join(desktopPath, `${path.basename(inputFolderPath)}-new.docx`)
await ZFolder(inputFolderPath, outputPath)
await fs.promises.rename(outputPath, finalDocxPath)
console.log(`created into ${finalDocxPath}`)
}
async function getXMLFilesContent (dirPath) {
const result = []
const currentFiles = await fs.promises.readdir(dirPath, { withFileTypes: true })
for (const fileInfo of currentFiles) {
if (fileInfo.isFile()) {
const fullPath = path.join(dirPath, fileInfo.name)
const content = await fs.promises.readFile(fullPath, { encoding: 'utf8' })
if (isXML(content)) {
result.push({
fullPath,
content
})
}
} else if (fileInfo.isDirectory()) {
const xmlFilesInDirectory = await getXMLFilesContent(path.join(dirPath, fileInfo.name))
result.push(...xmlFilesInDirectory)
}
}
return result
}
function isXML (str) {
return (/^\s*<[\s\S]*>/).test(str)
}
main()