-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·45 lines (34 loc) · 1.38 KB
/
cli.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
#!/usr/bin/env node
const path = require('path')
const fs = require('fs')
const [, , json, output] = process.argv
if (!json || !output) {
console.error('You need to add JSON with redirects and output folder as arguments:\n')
console.error('\thtml-redirections redirects.json dist')
process.exit(1)
}
const jsonFile = path.resolve(process.cwd(), json)
const outputDirectory = path.resolve(process.cwd(), output)
const jsonContents = JSON.parse(fs.readFileSync(jsonFile))
const redirects = Array.isArray(jsonContents) ? jsonContents : jsonContents.redirects
if (!redirects) {
const signature = `Array<{ from: string, to: string, delay?: number }>`
console.error('Your JSON file should have one of this structures:\n')
console.error('Direct array in JSON:')
console.error(`\n\t${signature}\n`)
console.error('Object with `redirects` field:')
console.error(`\n\t { redirects: ${signature} }\n`)
process.exit(1)
}
redirects.forEach(({ from, to, delay = 0, meta = [] }) => {
const pathname = new URL(from, 'https://localhost').pathname
const directory = path.join(outputDirectory, pathname)
fs.mkdirSync(directory, { recursive: true })
let addHtml = `<meta http-equiv="Refresh" content="${delay};url=${encodeURI(to)}">`
meta.forEach(({ name, content }) => {
addHtml += `<meta name="${name}" content="${content}">`
})
fs.writeFileSync(
path.join(directory, 'index.html'), addHtml
)
})