MCPcopy
hub / github.com/Unitech/pm2 / serveStaticFile

Function serveStaticFile

lib/API/Serve.js:393–449  ·  view source on GitHub ↗
(filePath, file, request, response)

Source from the content-addressed store, hash-verified

391}
392
393function serveStaticFile(filePath, file, request, response) {
394 var contentType = contentTypes[filePath.split('.').pop().toLowerCase()] || 'text/plain';
395
396 fs.readFile(filePath, function (error, content) {
397 if (error) {
398 if ((!options.spa || file === options.homepage)) {
399 console.error('[%s] Error while serving %s with content-type %s : %s',
400 new Date(), filePath, contentType, error.message || error);
401 }
402 //errorMeter.mark();
403 if (error.code === 'ENOENT') {
404 if (options.spa && !request.wantHomepage) {
405 request.wantHomepage = true;
406 return serveFile(`/${path.basename(file)}`, request, response);
407 } else if (options.spa && file !== options.homepage) {
408 return serveFile(options.homepage, request, response);
409 }
410 fs.readFile(options.path + '/404.html', function (err, content) {
411 content = err ? '404 Not Found' : content;
412 response.writeHead(404, { 'Content-Type': 'text/html' });
413 return response.end(content, 'utf-8');
414 });
415 return;
416 }
417 response.writeHead(500);
418 return response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
419 }
420
421 // Add CORS headers to allow browsers to fetch data directly
422 response.writeHead(200, {
423 'Content-Type': contentType,
424 'Access-Control-Allow-Origin': '*',
425 'Access-Control-Allow-Methods': 'GET'
426 });
427 if (options.monitorBucket && contentType === 'text/html') {
428 content = content.toString().replace('</body>', `
429<script>
430;(function (b,e,n,o,i,t) {
431 b[o]=b[o]||function(f){(b[o].c=b[o].c||[]).push(f)};
432 t=e.createElement(i);e=e.getElementsByTagName(i)[0];
433 t.async=1;t.src=n;e.parentNode.insertBefore(t,e);
434}(window,document,'https://apm.pm2.io/pm2-io-apm-browser.v1.js','pm2Ready','script'))
435
436pm2Ready(function(apm) {
437 apm.setBucket('${options.monitorBucket}')
438 apm.setApplication('${options.monitor}')
439 apm.reportTimings()
440 apm.reportIssues()
441})
442</script>
443</body>
444`);
445 }
446 response.end(content, 'utf-8');
447 debug('[%s] Serving %s with content-type %s', Date.now(), filePath, contentType);
448 });
449}
450

Callers 1

serveFileFunction · 0.85

Calls 4

serveFileFunction · 0.85
writeHeadMethod · 0.80
toStringMethod · 0.80
endMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…