var cp = require('child_process'),
_ = require('lodash'),
path = require('path'),
env = require('../lib/environment'),
webpackConfig = require('./webpack.server')(env)
let server
let pending = true
const {output} = webpackConfig
const serverPath = path.join(output.path,output.filename)
const RUNNING_REGXP = /server is running at \d+/
function runServer(){
return new Promise(function(resolve,reject){
function onStdout(data){
const time = new Date().toTimeString()
const match = data.toString().match(RUNNING_REGXP)
process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/,'[$1] '))
process.stdout.write(data)
if(match){
server.host = match[1]
server.stdout.removeListener('data',onStdout)
server.stdout.on('data',x=>process.stdout.write(x))
pending = false
resolve(server)
}
}
if(server){
server.kill('SIGTERM')
}
server = cp.spawn('node',['./app.js'],{
env:_.merge({},{NODE_ENV:'development'},process.env),
slient:false
})
if(pending){
server.once('exit',(code,signal)=>{
if(pending){
throw new Error(`Server terminated unexpectedly with code: ${code} signal: ${signal}`)
}
})
}
server.stdout.on('data',onStdout)
server.stderr.on('data',x=>process.stderr.write(x))
return server
})
}
process.on('exit',()=>{
if(server){
server.kill('SIGTERM')
}
})
module.exports = runServer