I'm new to Node and i'm really stuck.
I'm trying to make my web server to look up files in current directory and to display them in browser as links so i could download them.
However the list of files gets just updated with every request and displayed over and over. I can't use any frameworks or external components and i have been stuck on this for two days. I really have done a lot of research and tried a lot of things and still can't get it working.
I'm gonna add my last attempt's code below and if anyone could help me with even a little bit of information, it would be most appreciated. Thanks!
var http = require("http");
var fs = require("fs");
var currentServerDir = ".";
var port = 8080;
var content = "";
var server = http.createServer(handlerRequest).listen(8080);
function handlerRequest(request, response) {
fs.readdir(currentServerDir, function getFiles(error, items) {
items.forEach(function getItems(item) {
content += "<br><a href= " + "\" " + item + "\" " + ">" + item + "</a><br>";
});
});
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write(content);
response.end();
}
EDIT:
I followed Node.js Generate html
and borrowed some code from there. Now i can click on a file, but instead of downloading or viewing it just says "undefined".
var http = require('http');
var content
function getFiles()
{
fs.readdir(currentServerDir, function getFiles(error, items)
{
items.forEach(function getItems(item)
{
content+= "<br><a href= " + "\" " + item + "\" " + ">" +item + "</a><br>";
});
});
}
http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
}).listen(8080);
function buildHtml(req) {
var header = '';
var body = content;
return '<!DOCTYPE html>'
+ '<html><header>' + header + '</header><body>' + body + '</body> </html>';
};