Created
September 22, 2024 19:02
-
-
Save dougkusanagi/a9d614d4438808e770b51dc5c3dfa83c to your computer and use it in GitHub Desktop.
How to run artisan (or other commands) from node easylly
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
import { spawn } from "node:child_process"; | |
import { fileURLToPath } from "node:url"; | |
import path from "node:path"; | |
const __filename = fileURLToPath(import.meta.url); | |
const __dirname = path.dirname(__filename); | |
function startLaravelServer(config = {}) { | |
const { | |
host = "127.0.0.1", | |
port = "8000", | |
phpPath = path.join(__dirname, "php", "php.exe"), | |
laravelPath = path.join(__dirname, "www"), | |
env = {}, | |
runInBackground = false, | |
} = config; | |
const args = [ | |
path.join(laravelPath, "artisan"), | |
"serve", | |
`--host=${host}`, | |
`--port=${port}`, | |
]; | |
const spawnOptions = { | |
cwd: laravelPath, | |
stdio: runInBackground ? "ignore" : ["ignore", "pipe", "pipe"], | |
detached: runInBackground, | |
env: { ...process.env, ...env }, | |
}; | |
const laravelProcess = spawn(phpPath, args, spawnOptions); | |
if (runInBackground) { | |
laravelProcess.unref(); | |
console.log( | |
`Laravel Server started in background on http://${host}:${port}`, | |
); | |
} else { | |
laravelProcess.stdout.on("data", (data) => { | |
console.log(`Laravel Server stdout: ${data}`); | |
}); | |
laravelProcess.stderr.on("data", (data) => { | |
console.error(`Laravel Server stderr: ${data}`); | |
}); | |
laravelProcess.on("exit", (code, signal) => { | |
if (code) console.log(`Laravel Server process exited with code ${code}`); | |
if (signal) | |
console.log(`Laravel Server process was killed with signal ${signal}`); | |
}); | |
laravelProcess.on("error", (err) => { | |
console.error("Failed to start Laravel Server:", err); | |
}); | |
console.log(`Laravel Server starting on http://${host}:${port}`); | |
} | |
return laravelProcess; | |
} | |
// if runned directly exec the function | |
if (require.main === module) { | |
startLaravelServer(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment