-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
|
||
const SCRIPT = | ||
`<script async src="https://www.googletagmanager.com/gtag/js?id=G-8N9MBTQKCK"></script> | ||
<script> | ||
window.dataLayer = window.dataLayer || []; | ||
function gtag() { | ||
dataLayer.push(arguments); | ||
} | ||
gtag('js', new Date()); | ||
gtag('config', 'G-8N9MBTQKCK'); | ||
</script>`; | ||
|
||
function appendGa(path) { | ||
let html = fs.readFileSync(path, 'utf8'); | ||
if (html.includes(SCRIPT)) { | ||
console.log(`👌 ${path} already has tracking`); | ||
return; | ||
} | ||
const pos = html.lastIndexOf('</body>'); | ||
if (pos < 0) { | ||
throw new Error('Could not find </body> tag'); | ||
} | ||
html = html.substring(0, pos) + SCRIPT + html.substring(pos); | ||
fs.writeFileSync(path, html, 'utf8'); | ||
console.log(`✅ ${path} updated`); | ||
} | ||
|
||
const directory = process.argv[2]; | ||
if (!directory) { | ||
throw new Error('Please specify a directory'); | ||
} | ||
|
||
const dirPath = path.join(__dirname, '..', directory); | ||
fs.readdir(dirPath, (_, files) => { | ||
files.forEach(file => { | ||
if (file.endsWith('.html')) { | ||
const filePath = path.join(dirPath, file); | ||
appendGa(filePath); | ||
} | ||
}); | ||
}); |