Geo
Geo

Reputation: 144

Open pdf files in simple Node.js web page

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:

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?

Upvotes: 0

Views: 7249

Answers (1)

generalhenry
generalhenry

Reputation: 17319

// 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 . . .

Upvotes: 3

Related Questions