So, I'm learning node, tried to write simple server by my self. When it comes to write data to response, it doesn't work properly. I converted data to String, i tried to display data to the console and it had benn displayed normally, but when I pass it to response.write() nothing changes at my page. I created file called 'lorem' in poems/lorem directory, I write this path to my link in browser. As you can see, I was writting some debugging stuff, but I deleted most of it.
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);
There some console output for 'C:/folderpath/ node server.js 8080' cmd:
Server is lisntening on port 8080
lorem
lorem
lorem
Content of 'poems/lorem' file == 'lorem'
Aucun commentaire:
Enregistrer un commentaire