Loading basic HTML in Node.js

后端 未结 20 1347
暗喜
暗喜 2020-11-28 17:34

I\'m trying to find out how to load and render a basic HTML file so I don\'t have to write code like:

response.write(\'...

blahblahblah

...\
20条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 17:55

    It's just really simple if you use pipe. The following is the server.js code snippet.

    var http = require('http');
    var fs = require('fs');
    
    function onRequest(req, res){
    
        console.log("USER MADE A REQUEST. " +req.url);
        res.writeHead(200, {'Content-Type': 'text/html'});
        var readStream = fs.createReadStream(__dirname + '/index.html','utf8'); 
        
    /*include your html file and directory name instead of <<__dirname + '/index.html'>>*/
    
        readStream.pipe(res);
    
    }
    
    http.createServer(onRequest).listen(7000);
    console.log('Web Server is running...');

提交回复
热议问题