JS: update and prettify examples

This commit is contained in:
Esben Sparre Andreasen
2021-01-22 13:17:38 +01:00
parent 5a6e692807
commit 718f6eb3fd
3 changed files with 20 additions and 20 deletions

View File

@@ -1,21 +1,22 @@
const express = require("express"),
fs = require("fs");
fs = require("fs");
function save(rootDir, path, content){
if (!isValidPath(rootDir, req.query.filePath)) {
throw new Error(`Invalid filePath: ${req.query.filePath}`); // BAD crashes the server
}
// write content to disk
function save(rootDir, path, content) {
if (!isValidPath(rootDir, req.query.filePath)) {
throw new Error(`Invalid filePath: ${req.query.filePath}`); // BAD crashes the server
}
// write content to disk
}
express().post("/save", (req, res) => {
fs.access(rootDir, (err) => {
if (err) {
console.error(`Server setup is corrupted, ${rootDir} does not exist!`);
res.status(500);
res.end();
}
save(rootDir, req.query.path, req.body);
res.status(200);
res.end();
});
fs.exists(rootDir, (exists) => {
if (!exists) {
console.error(`Server setup is corrupted, ${rootDir} does not exist!`);
res.status(500);
res.end();
return;
}
save(rootDir, req.query.path, req.body);
res.status(200);
res.end();
});
});

View File

@@ -1,6 +1,6 @@
// ...
express().post("/save", (req, res) => {
fs.access(rootDir, (err) => {
fs.exists(rootDir, (exists) => {
// ...
try {
save(rootDir, req.query.path, req.body); // GOOD no uncaught exception

View File

@@ -1,11 +1,10 @@
// ...
express().post("/save", async (req, res) => {
try {
await fs.access(rootDir);
} catch (e) {
if (await fs.promises.exists(rootDir)) {
console.error(`Server setup is corrupted, ${rootDir} does not exist!`);
res.status(500);
res.end();
return;
}
save(rootDir, req.query.path, req.body); // MAYBE BAD, depends on the commandline options
res.status(200);