使用nodejs服务器读取和打印文件内容?

时间:2018-06-03 00:09:50

标签: javascript node.js curl

你好我使用docker和ansible来启动一个容器,然后启动一个server.js文件,该文件需要显示位于同一目录下的index.html文件的内容。我有这个骨架轮廓代码,可用于显示" Hello World"当我卷曲运行此server.js文件的IP地址

时到屏幕
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8080);
console.log('Server started');

console.log没有显示在屏幕上,看起来只有响应。这样做,打印' Hello World'到了屏幕,所以我一直试图在index.html文件中读取变量并有响应。显示它但没有运气。

我试过这样做:

var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});

var fs = require('fs');
var readStream = fs.createReadStream('index.html');
readStream.pipe(response); 

//response.end('Hello World\n');
}).listen(8080);
console.log('Server started');

但是当我试图卷曲它时,它导致服务器发出一个错误的52空回复,我是不是在读取我的index.html文件并将其存储为字符串变量?谢谢。

1 个答案:

答案 0 :(得分:0)

var http = require('http');
var fs = require("fs");
http.createServer(function(req, res) {
 fs.readFile("index.html","utf8" ,function(err, contents){
 console.log(contents);
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.write(contents);
 res.end();
 });
}).listen(3000);

if you want to show the contents of the file on  request to the server try this.

相关问题