Read a file in Node.js

后端 未结 8 1111
礼貌的吻别
礼貌的吻别 2020-11-27 10:22

I\'m quite puzzled with reading files in Node.js.

fs.open(\'./start.html\', \'r\', function(err, fileToRead){
    if (!err){
        fs.readFile(fileToRead,         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 11:01

    To read the html file from server using http module. This is one way to read file from server. If you want to get it on console just remove http module declaration.

    var http = require('http');
    var fs = require('fs');
    var server = http.createServer(function(req, res) {
      fs.readFile('HTMLPage1.html', function(err, data) {
        if (!err) {
          res.writeHead(200, {
            'Content-Type': 'text/html'
          });
          res.write(data);
          res.end();
        } else {
          console.log('error');
        }
      });
    });
    server.listen(8000, function(req, res) {
      console.log('server listening to localhost 8000');
    });
    
    
    
      

    My Header

    My paragraph.

提交回复
热议问题