Skip to content

Instantly share code, notes, and snippets.

@martiuh
Last active February 23, 2019 19:29
Show Gist options
  • Save martiuh/6cd43185a4aac16e147001b9163dfcad to your computer and use it in GitHub Desktop.
Save martiuh/6cd43185a4aac16e147001b9163dfcad to your computer and use it in GitHub Desktop.
Build hook for node app.
/*
Server for make a self-building gatsby site
Build by Tonatiuh González <martiuh@gmail.com>
with love to the community
*/
const http = require('http')
const fs = require('fs')
const { spawn, exec } = require('child_process')
const port = process.env.NODE_ENV ? parseInt(process.env.NODE_ENV, 10) : 3000
// ls.stdout.on('data', data => {
// console.log(`stdout: ${data}`);
// });
// ls.stderr.on('data', data => {
// console.log(`stderr: ${data}`);
// });
// ls.on('close', code => {
// console.log(`child process exited with code ${code}`);
// });
const moveToProductionBuild = (buildCode, moveCode, res) => {
if (buildCode === 0 && moveCode === buildCode) {
res.writeHead(200, {
'Content-Type': 'text/html',
})
const buildString = `build and moved ${Date.now()}`
console.log(buildString)
res.write(`<small>${buildString}</small>`)
return res.end()
} else {
res.writeHead(500)
res.write('<small>Error: during build time</small>')
res.end()
}
}
const buildCommand = (err, res) => {
if (err) {
return console.log(err)
}
const build = spawn('npm', ['run', 'build'], {})
build.on('close', buildCode => {
const overWriteAll = exec('cp -r public/* production_public/', {
shell: true,
})
overWriteAll.on('close', moveCode => {
moveToProductionBuild(buildCode, moveCode, res)
})
})
}
const ensureProductionPublic = res => {
const productionPublicLocation = `${__dirname}/production_public`
fs.readdir(productionPublicLocation, err => {
if (err) {
if (err.code === 'ENOENT') {
console.log('making new directory')
return fs.mkdir(productionPublicLocation, err => {
buildCommand(err, res)
})
}
}
console.log('production_public exists')
return buildCommand(null, res)
})
}
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/martiuh') {
console.log('HEHEHE')
ensureProductionPublic(res)
} else {
res.writeHead(200, {
'Content-Type': 'text/html',
})
res.write('<small>200</small>')
res.end()
}
})
server.listen(port, () => console.log(`running on port: ${port}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment