0

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:

  1. The "id" variable has to be read from the URL
  2. Then, only the .PDF files in the directory ./files/id/ have to be read and listed -- where "id" is the variable from 1.
  3. 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?

2
  • I have also tried to make the "html" variable a html file and add for each file in the dir html += "<a href='" + pdfdir + file + "'>" + file + "</a><br/>"; Nothing happens though when i click the link... Commented Apr 2, 2018 at 23:06
  • One way is to do this with Express as that's a lot easier than mashing around with raw http. Commented Apr 2, 2018 at 23:15

1 Answer 1

3
// imports first
const
  http = require('http'),
  url = require('url'),
  querystring = require('querystring'),
  fs = require('fs'),
  path = require('path');

const
  hostname = '127.0.0.1',
  port = 3000;

// main function should only route requests
const server = http.createServer((req, res) => {
  const params = querystring.parse(url.parse(req.url).query);
  if ('id' in params) {
    handleDirectoryListing(req, res, params)
  } else if ('file' in params) {
    handleServeFile(req, res, params)
  } else {
    res.statusCode = 404
    res.end('Incorrect link');
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

function handleDirectoryListing (req, res, params) {
  const pdfdir = `./files/${params.id}/`;
  console.log(pdfdir);
  // never use sync in an http handler
  fs.readdir(pdfdir, function (err, files) {
    if (err) {
      res.statusCode = 404;
      res.end('directory not found');
    } else {
      let html = `<!DOCTYPE html>
<meta charset="utf-8">
<title>Test page</title>          
<h1>Test page</h1>
<div>id: ${params.id}</div>
`;
      html += files.map(file => {
        const filepath = path.join(pdfdir, file);
        console.log(filepath);
        return `<dir>File: <a href="/?${querystring.stringify({file: filepath})}">${pdfdir}${file}</a></dir>`;
      }).join('\n');
      res.end(html);
    }
  });
}

// serving files is easy, but note, this is not secure or efficient
function handleServeFile (req, res, params) {
  const filepath = path.join(__dirname, params.file);
  fs.createReadStream(filepath).pipe(res);
}

Though once you grasp it you should use a module such as express to make it clean, secure, efficient etc . . .

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works and explains perfectly how to proceed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.