80 lines
2.5 KiB
JavaScript
80 lines
2.5 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const Joi = require('joi');
|
|
const fetch = require('node-fetch');
|
|
const { httpStatus } = require('../helpers/http_status');
|
|
|
|
const app = express();
|
|
app.use(express.json());
|
|
|
|
const filePathSchema = Joi.object({
|
|
filePath: Joi.string().required()
|
|
});
|
|
|
|
async function getBaseDirectory() {
|
|
const filePath = path.join(__dirname, '..', 'dirBackup.json');
|
|
try {
|
|
const data = await fs.promises.readFile(filePath, 'utf8');
|
|
const jsonData = JSON.parse(data);
|
|
return jsonData.path;
|
|
} catch (error) {
|
|
console.error('Error reading the base directory:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
app.post('/file_path', async (req, res) => {
|
|
const { error, value } = filePathSchema.validate(req.body);
|
|
if (error) {
|
|
return res.status(httpStatus.BAD_REQUEST).json({
|
|
message: 'Invalid input',
|
|
data: error.details
|
|
});
|
|
}
|
|
|
|
try {
|
|
const basePath = await getBaseDirectory();
|
|
let { filePath } = value;
|
|
const baseDirName = path.basename(basePath);
|
|
if (filePath.startsWith(baseDirName + path.sep)) {
|
|
filePath = filePath.slice(baseDirName.length + 1);
|
|
}
|
|
const fullPath = path.resolve(basePath, filePath);
|
|
|
|
fs.stat(fullPath, (err, stats) => {
|
|
if (err) {
|
|
if (err.code === 'ENOENT') {
|
|
return res.status(httpStatus.NOT_FOUND).json({
|
|
message: 'File not found'
|
|
});
|
|
}
|
|
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
|
|
message: 'Error accessing the file'
|
|
});
|
|
}
|
|
|
|
if (!stats.isFile()) {
|
|
return res.status(httpStatus.BAD_REQUEST).json({
|
|
message: 'Path is not a file'
|
|
});
|
|
}
|
|
|
|
// Stream the file as binary data
|
|
res.writeHead(httpStatus.OK, {
|
|
'Content-Type': 'application/octet-stream',
|
|
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
|
|
});
|
|
const fileStream = fs.createReadStream(fullPath);
|
|
fileStream.pipe(res);
|
|
});
|
|
} catch (error) {
|
|
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
|
|
message: 'Error processing request'
|
|
});
|
|
}
|
|
});
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|