Skip to content

Instantly share code, notes, and snippets.

@rezonn
Last active May 5, 2020 11:14
Show Gist options
  • Save rezonn/1710744828c8ad6e2be358f01612c98d to your computer and use it in GitHub Desktop.
Save rezonn/1710744828c8ad6e2be358f01612c98d to your computer and use it in GitHub Desktop.
Native NodeJS server. File list in JSON, get and push files. run shell
var fs = require('fs');
var paths = [
__dirname+"/data",
__dirname,
];
mimeTypes = {
"html": "text/html",
"htm": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
require('http').createServer(function (req, res) {
console.log(req.method+" "+decodeURI(req.url));
if (req.method=="GET") {
for (var i=0;i<paths.length;i++) {
var path = paths[i] + decodeURI(req.url).split("?")[0]||req.url;
var mime = mimeTypes[path.split('.').pop()] || "text/plain";
if (fs.existsSync(path)) {
if (fs.statSync(path).isFile()) {
res.writeHead(200, {'Content-Type': mime});
var stream = fs.createReadStream(path);
stream.on("open",function(){
stream.pipe(res);
});
stream.on("error",function(err){
res.end(err);
});
return;
}
else if (fs.statSync(path).isDirectory()) {
res.writeHead(200, {"Content-Type": "text/json; charset=utf-8"});
res.end(JSON.stringify(fs.readdirSync(path).map(file => {
return file;
})));
return;
}
}
}
}
else if (req.method=="POST") {
for (var i=0;i<1;i++) {
var path = paths[i] + decodeURI(req.url).split("?")[0]||req.url;
var folder = path.split(/\//).slice(0,-1).join("//");
if (!fs.existsSync(folder)) fs.mkdirSync(folder);
var stream = fs.createWriteStream(path);
stream.on("open",function(){
req.pipe(stream);
});
stream.on("error",function(err){
res.end("error save");
});
stream.on("finish",function(){
res.end();
});
return;
}
}
else if (req.method=="PATCH") {
var cmd = decodeURI(req.url).slice(1);
require("child_process").exec(cmd,{},function(error,stdout,stderr){
res.end([error,stdout,stderr].filter(function(a){return a}).join("\n"));
});
return;
}
else {
res.writeHead(405, {'Content-Type': 'text/plain; charset=utf-8' });
res.end(req.method + " "+req.url+" Method Not Allowed");
return;
}
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(req.method + " "+req.url+" Bad Request");
return;
}).listen(8001);
console.log("http://localhost:8001");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment