我正在尝试在node.js中创建一个网页,其中列出了URL中变量定义的文件夹中的所有pdf文件。当用户点击一个pdf链接时,该文件应该打开。
可悲的是,作为一个完整的node.js / javascript初学者,我无法弄清楚如何去做。
URL: http://127.0.0.1:3000/?id=1001
OS: Windows Server 2012 R2
应该做的步骤:
我设法做的事情:
代码下方:
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}/`);
});
有人可以指导下一步吗?
答案 0 :(得分:1)
// 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);
}
虽然一旦掌握了它,你应该使用快递等模块,使其干净,安全,高效等。 。