How to run html file using node js

前端 未结 8 845
南笙
南笙 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);
    
    0 讨论(0)
  • 2021-01-30 11:45

    This is a simple html file "demo.htm" stored in the same folder as the node.js file.

    <!DOCTYPE html>
    <html>
      <body>
        <h1>Heading</h1>
        <p>Paragraph.</p>
      </body>
    </html>
    

    Below is the node.js file to call this html file.

    var http = require('http');
    var fs = require('fs');
    
    var server = http.createServer(function(req, resp){
      // Print the name of the file for which request is made.
      console.log("Request for demo file received.");
      fs.readFile("Documents/nodejs/demo.html",function(error, data){
        if (error) {
          resp.writeHead(404);
          resp.write('Contents you are looking for-not found');
          resp.end();
        }  else {
          resp.writeHead(200, {
            'Content-Type': 'text/html'
          });
          resp.write(data.toString());
          resp.end();
        }
      });
    });
    
    server.listen(8081, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:8081/');
    

    Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".

    0 讨论(0)
提交回复
热议问题