How to run html file using node js

前端 未结 8 866
南笙
南笙 2021-01-30 11:04

I have a simple html page with angular js as follows:

    //Application name
    var app = angular.module(\"myTmoApppdl\", []);

    app.controller(\"myCtrl\", f         


        
8条回答
  •  醉梦人生
    2021-01-30 11:44

    Either you use a framework or you write your own server with nodejs.

    A simple fileserver may look like this:

    import * as http from 'http';
    import * as url from 'url';
    import * as fs from 'fs';
    import * as path from 'path';
    
    var mimeTypes = {
         "html": "text/html",
         "jpeg": "image/jpeg",
         "jpg": "image/jpeg",
         "png": "image/png",
         "js": "text/javascript",
         "css": "text/css"};
    
    http.createServer((request, response)=>{
        var pathname = url.parse(request.url).pathname;
        var filename : string;
        if(pathname === "/"){
            filename = "index.html";
        }
        else
            filename = path.join(process.cwd(), pathname);
    
        try{
            fs.accessSync(filename, fs.F_OK);
            var fileStream = fs.createReadStream(filename);
            var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
            response.writeHead(200, {'Content-Type':mimeType});
            fileStream.pipe(response);
        }
        catch(e) {
                console.log('File not exists: ' + filename);
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.write('404 Not Found\n');
                response.end();
                return;
        }
        return;
        }
    }).listen(5000);
    

提交回复
热议问题