Check out this simple implementation:
You save the download information in a file. The file name is the identifier of the download session. The contents of the file is the real path to the file to be downloaded.
:
var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
const DL_SESSION_FOLDER = '/var/download_sessions';
function createDownload(filePath, callback) {
if (!fs.existsSync(DL_SESSION_FOLDER)) return callback(new Error('Session directory does not exist'));
if (!fs.existsSync(filePath)) return callback(new Error('File doest not exist'));
var downloadSid = crypto.createHash('md5').update(Math.random().toString()).digest('hex');
var dlSessionFileName = path.join(DL_SESSION_FOLDER, downloadSid + '.download');
fs.writeFile(dlSessionFileName, filePath, function(err) {
if (err) return callback(err);
callback(null, downloadSid);
});
}
function getDownloadFilePath(downloadSid, callback) {
var dlSessionFileName = path.join(DL_SESSION_FOLDER, downloadSid + '.download');
if (!fs.existsSync(dlSessionFileName)) return callback(new Error('Download does not exist'));
fs.readFile(dlSessionFileName, function(err, data) {
if (err) return callback(err);
callback(null, data);
});
}
function deleteDownload(downloadSid, callback) {
var dlSessionFileName = path.join(DL_SESSION_FOLDER, downloadSid + '.download');
if (!fs.existsSync(dlSessionFileName)) return callback(new Error('Download does not exist'));
fs.unlink(dlSessionFileName, function(err) {
if (err) return callback(err);
callback();
});
}
createDownload() , . sid, URL- , : http://your.server.com/download?sid=<RETURNED SID>.
, /download:
app.get('/download', function(req, res, next) {
var downloadSid = req.query.sid;
getDownloadFilePath(downloadSid, function(err, path) {
if (err) return res.end('Error');
deleteDownload(downloadSid, function(err) {
});
});
});
// , .