【问题标题】:read and print file contents with nodejs server?使用 nodejs 服务器读取和打印文件内容?
【发布时间】:2018-06-03 00:09:50
【问题描述】:

你好,我正在使用 docker 和 ansible 来启动一个容器,然后该容器将启动一个 server.js 文件,该文件需要显示位于同一目录中的 index.html 文件的内容。我有这个框架大纲代码,当我 curl 运行这个 server.js 文件的 IP 地址时,它可以在屏幕上显示“Hello World”

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 不会显示在屏幕上,似乎只有 response.end 会这样做,并在屏幕上打印“Hello World”,所以我一直在尝试将 index.html 文件作为变量读取,并且有 response.end 显示它,但没有运气。

我试过这样做:

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 文件并将其存储为字符串变量方面做得不够吗?谢谢。

【问题讨论】:

  • Node 控制台中是否有任何错误?
  • 我需要包含错误处理吗?

标签: javascript node.js curl


【解决方案1】:

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.

【讨论】:

    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多