I am trying to create a web page in node.js which lists all pdf files in a folder defined by a variable in the URL. When a user clicks on one pdf link, the file should open.
Sadly, being a total node.js/javascript beginner, I can't figure out how to do it.
URL: http://127.0.0.1:3000/?id=1001
OS: Windows Server 2012 R2
Steps which should be done:
- The "id" variable has to be read from the URL
- Then, only the .PDF files in the directory ./files/id/ have to be read and listed -- where "id" is the variable from 1.
- Then, when the user clicks one of them, it should open in the browser (Chrome)
What I managed to do:
- set up the web server
- parse the URL for the id value
- dir the id folder
- display the files
Below the code:
const
http = require('http'),
hostname = '127.0.0.1',
port = 3000,
querystring = require('querystring'),
url = require('url'),
fs = require('fs');
const server = http.createServer((req, res) => {
const params = querystring.parse(url.parse(req.url).query);
if ('id' in params) {
let html = "Test page\n"
html += "id: " + params.id + "\n";
const pdfdir = "./files/" + params.id + "/";
console.log(pdfdir);
let files = fs.readdirSync(pdfdir);
files.forEach(file => {
const filepath = __dirname + pdfdir + file;
console.log(filepath);
html += "File: " + pdfdir + file + "\n";
});
res.write(html);
}
else {
res.write('Incorrect link');
}
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Can somebody please guide me with the next steps?
html += "<a href='" + pdfdir + file + "'>" + file + "</a><br/>";Nothing happens though when i click the link...http.