Skip to content

Instantly share code, notes, and snippets.

@mvictorl
Created July 11, 2022 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvictorl/7be53a0c61ec7ccb8933e5de3f34289d to your computer and use it in GitHub Desktop.
Save mvictorl/7be53a0c61ec7ccb8933e5de3f34289d to your computer and use it in GitHub Desktop.
Insert <script> block into template.html BEFORE </body> tag (Node.js)
const fsp = require('fs').promises
const readFilePath = './template.html'
const writeFilePath = './index.html'
const block = `
<script>
const eventSource = new EventSource('http://localhost:3000/subscribe')
eventSource.onerror = () => { console.log('Error with live-server') }
eventSource.onmessage = () => { window.location.reload() }
</script>
`
fsp
.readFile(readFilePath, 'utf-8')
.then(data => data.replace(/\<\/body>/, block + '$&'))
.then(data => fsp.writeFile(writeFilePath, data, 'utf-8'))
.catch(err => console.error(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment