@striven-erp/striven-fileviewer
Version:
A pure javascript fileviewer made for Striven ERP
41 lines (31 loc) • 1.26 kB
JavaScript
const path = require('path');
const fs = require('fs');
const app = require('express')();
const PORT = 4200;
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '100mb'}));
app.get('/', (req, res) => res.send('WORKING'));
app.post('/temp/file', (req, res) => {
const filePath = path.join(__dirname, `${req.body.fileName}.${req.body.fileType}`);
fs.writeFile(filePath, req.body.file, { encoding: 'base64' }, err => { if (err) { console.log(err) } });
res.send(`http://localhost:4200/temp/file/${req.body.fileName}/${req.body.fileType}`);
})
app.get('/temp/file/:filename/:filetype', (req, res) => {
const filePath = path.join(__dirname, `${req.params.filename}.${req.params.filetype}`);
const stream = fs.createReadStream(filePath, { bufferSize: 64 * 1024 });
stream.pipe(res);
let errorOccured = false;
stream.on('error', function (err) {
errorOccured = true;
});
stream.on('close', () => {
if (!errorOccured) {
fs.unlink(filePath, (err) => {
err && console.log(err);
});
}
})
})
app.listen(PORT, () => console.log('Server on.'))