node.js - 其中包括 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());
}
预先感谢您的帮助。
解决方案
如果您想读取文件并将其发送给客户端,您可以执行以下操作:
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}/`);
});
推荐阅读
- kotlin - Kotlin 中学班建设者
- java - 为什么spring-data-redis ZSetOperations范围操作返回Set而不是SortedSet?
- c++ - Number 和 Shape 超类中的 vtable 错误
- kubernetes - 在本地 Kubernetes 集群上安装 OpenFaas
- loadrunner - 负载运行器中的巨大响应时间
- aframe - 如何在 Aframe 中使模型 glft 居中?
- firebase - firebase 实时数据库分片规则
- vue.js - 如何在 datepicker vuetify 中添加加载?
- python - 如何使用 Python pandas-datareader 0.8 从 Alpha Vantage 正确调用数据
- python - 如何在 swig 中使用 numpy.i?