serve.js 836 B

1234567891011121314151617181920212223242526272829303132
  1. const http = require( 'http' );
  2. const path = require( 'path' );
  3. const fs = require( 'fs' ).promises;
  4. const server = http.createServer();
  5. const mime = {
  6. '.html': 'text/html',
  7. '.css' : 'text/css',
  8. '.jpg' : 'image/jpeg',
  9. '.js' : 'application/javascript',
  10. };
  11. server.on( 'request', async ( request, response ) => {
  12. const { url } = request;
  13. let fullPath;
  14. if ( url === '/' ) {
  15. fullPath = path.resolve( './src/js/test/html/index.html' );
  16. } else if ( url.startsWith( '/' ) ) {
  17. fullPath = path.resolve( `.${ url }` );
  18. } else {
  19. fullPath = url;
  20. }
  21. const type = mime[ path.extname( fullPath ) ] || 'text/plain';
  22. const buffer = await fs.readFile( fullPath ).catch( e => console.warn( e ) );
  23. response.writeHead( 200, { 'Content-Type': type } );
  24. response.end( buffer );
  25. } );
  26. server.listen( 3000 );