Init project
This commit is contained in:
75
server.js
Normal file
75
server.js
Normal file
@@ -0,0 +1,75 @@
|
||||
/* --- IMPORTS -------------------------- */
|
||||
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const concatStream = require('concat-stream');
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const config = require('./config');
|
||||
|
||||
/* --- SETUP ---------------------------- */
|
||||
|
||||
// Express
|
||||
const app = express();
|
||||
app.use((req, res, next) => {
|
||||
req.pipe(concatStream((data) => {
|
||||
req.rawBody = data;
|
||||
next();
|
||||
}));
|
||||
});
|
||||
app.use(bodyParser.json());
|
||||
app.use(bodyParser.urlencoded({ 'extended': false }));
|
||||
|
||||
/* --- FUNCTION ------------------------- */
|
||||
|
||||
function mkdir(dir) {
|
||||
if (fs.existsSync(dir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let d = path.dirname(dir);
|
||||
if (!fs.existsSync(d)) {
|
||||
mkdir(d);
|
||||
}
|
||||
fs.mkdirSync(dir);
|
||||
}
|
||||
|
||||
function toOsPath(urlPath) {
|
||||
return config.maven.dir + urlPath.substr(config.maven.url.length + 1);
|
||||
}
|
||||
|
||||
/* --- ROUTING -------------------------- */
|
||||
|
||||
app.route(`/${config.maven.url}/*`)
|
||||
.get((req, res) => {
|
||||
let osPath = toOsPath(req.path);
|
||||
fs.exists(osPath, (value) => {
|
||||
if (!value) {
|
||||
res.status(404).send();
|
||||
} else {
|
||||
res.status(200);
|
||||
res.sendFile(osPath);
|
||||
}
|
||||
});
|
||||
})
|
||||
.put((req, res) => {
|
||||
let osPath = toOsPath(req.path);
|
||||
mkdir(path.dirname(osPath));
|
||||
|
||||
fs.writeFile(osPath, req.rawBody, (err) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
res.status(500).send();
|
||||
} else {
|
||||
res.status(200).send();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/* --- START APP ------------------------ */
|
||||
|
||||
console.info(`Start web server :: ${config.web.host}:${config.web.port}`);
|
||||
app.listen(config.web.port, config.web.host);
|
||||
Reference in New Issue
Block a user