首页 > 解决方案 > 其中包括 data.toString()

问题描述

我想读取格式的文件html

const http = require('http');
const hostname = 'localhost';
const port = 3000;
const fs = require('fs');

// createServer = créer le serveur
const server = http.createServer((req, res) => {
    fs.readFile('index.html', (err, data) => {
        if(err){
            res.writeHead(404);
            res.end("Ce fichier n'existe pas");
        } else {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain');
            res.end('Hello World ');
            //console.log(data.toString());
        }  
    })
});

server.listen(port, hostname, () => {
  console.log(`Server running at   http://${hostname}:${port}/`);
});

我想知道我必须在哪里包含data.toString在我的代码中?

 console.log(data.toString());

我可以把它放进我的else?

else {
       res.statusCode = 200;
       res.setHeader('Content-Type', 'text/plain');
       res.end('Hello World ');
        //console.log(data.toString());
 } 

预先感谢您的帮助。

标签: node.js

解决方案


如果您想读取文件并将其发送给客户端,您可以执行以下操作:

const http = require('http');
const hostname = 'localhost';
const port = 3000;
const fs = require('fs');

// createServer = créer le serveur
const server = http.createServer((req, res) => {
    fs.readFile('index.html', (err, data) => {
        if(err){
            res.writeHead(404);
            res.end("Ce fichier n'existe pas");
        } else {
            const htmlText = data.toString(); // just create a variable and send it to the client or do whatever you want
            console.log(htmlText)
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.send(htmlText);
            //console.log(data.toString());
        }  
    })
});

server.listen(port, hostname, () => {
  console.log(`Server running at   http://${hostname}:${port}/`);
});

推荐阅读