因此,我正在学习节点,尝试自己编写简单的服务器。将数据写入响应时,它将无法正常工作。我将数据转换为String,我尝试将数据显示到控制台,并且benn正常显示,但是当我将其传递给response.write()时,页面上没有任何变化。我在poems / lorem目录中创建了名为“ lorem”的文件,并将此路径写入浏览器中的链接。 如您所见,我正在编写一些调试资料,但是我删除了大部分。
var http = require('http');
var fs = require('fs');
var path = require('path');
var port = process.argv[2];
var readFileContent = (filePath) =>
{
var readData = '';
fs.readFile(path.normalize(process.cwd() + filePath), 'utf-8', (err, data) =>
{
let invalid = false;
if(err || data === undefined)
{
invalid = true;
}
if(!invalid) readData = data;
console.log(readData); // logs data from a file
});
return readData;
}
var serverHandler = (request, response) =>
{
let responseData = readFileContent(request.url);
if(responseData != undefined)
{
response.writeHead(200, {'Content-Type':'text/html'});
response.write(''+ responseData.toString()); // there is a problem: writes data only when I pass some exact string (e.g. 'LOREM')
}
else{
response.writeHead(404);
response.write('Error occured');
}
response.end(responseData.toString());
}
http.createServer(serverHandler).listen(+ port);
console.log('Server is lisntening on port ' + port);
对于“ C:/ folderpath / node server.js 8080” cmd,有一些控制台输出:
Server is lisntening on port 8080
lorem
lorem
lorem
'poems / lorem'文件的内容=='lorem'
答案 0 :(得分:0)
我认为您的问题与异步性有关。
为文件读取功能提供回调,该回调返回文件内容。
赞:
var readFileContent = (filePath, callback) =>
{
fs.readFile(path.normalize(process.cwd() + filePath), 'utf-8', (err, data) =>
{
let invalid = false;
if(err || data === undefined)
{
invalid = true;
}
if(!invalid) readData = data;
callback(readData)
});
}
然后在服务器处理程序函数中执行以下操作:
var serverHandler = (request, response) =>
{
readFileContent(request.url, (responseData) => {
if(responseData != undefined) {
response.writeHead(200, {'Content-Type':'text/html'});
response.write(''+ responseData.toString());
}
else {
response.writeHead(404);
response.write('Error occured');
}
response.end(responseData.toString());
});
}