Loading basic HTML in Node.js

后端 未结 20 1343
暗喜
暗喜 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 18:02

    You can echo files manually using the fs object, but I'd recommend using the ExpressJS framework to make your life much easier.

    ...But if you insist on doing it the hard way:

    var http = require('http');
    var fs = require('fs');
    
    http.createServer(function(req, res){
        fs.readFile('test.html',function (err, data){
            res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
            res.write(data);
            res.end();
        });
    }).listen(8000);
    

提交回复
热议问题