in packages/docusaurus/src/commands/serve.ts [17:76]
export async function serve(
siteDir: string,
cliOptions: ServeCLIOptions,
): Promise<void> {
let dir = path.resolve(siteDir, cliOptions.dir);
if (cliOptions.build) {
dir = await build(
siteDir,
{
config: cliOptions.config,
outDir: dir,
},
false,
);
}
const host: string = getCLIOptionHost(cliOptions.host);
const port: number | null = await getCLIOptionPort(cliOptions.port, host);
if (port === null) {
process.exit();
}
const {
siteConfig: {baseUrl, trailingSlash},
} = await loadSiteConfig({
siteDir,
customConfigFilePath: cliOptions.config,
});
const servingUrl = `http://${host}:${port}`;
const server = http.createServer((req, res) => {
// Automatically redirect requests to /baseUrl/
if (!req.url?.startsWith(baseUrl)) {
res.writeHead(302, {
Location: baseUrl,
});
res.end();
return;
}
// Remove baseUrl before calling serveHandler, because /baseUrl/ should
// serve /build/index.html, not /build/baseUrl/index.html (does not exist)
req.url = req.url?.replace(baseUrl, '/');
serveHandler(req, res, {
cleanUrls: true,
public: dir,
trailingSlash,
directoryListing: false,
});
});
logger.success`Serving path=${cliOptions.dir} directory at url=${
servingUrl + baseUrl
}.`;
server.listen(port);
}