Skip to content

Instantly share code, notes, and snippets.

@ChugunovRoman
Created June 21, 2018 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChugunovRoman/e1503deef360bba8abc7c4e009e68a6a to your computer and use it in GitHub Desktop.
Save ChugunovRoman/e1503deef360bba8abc7c4e009e68a6a to your computer and use it in GitHub Desktop.
Express static server with Read/Write json file
/**
* Server side for issuance client scripts
*/
import path from "path";
import Express from 'express';
import BodyParser from "body-parser";
import { readFile, writeFile } from "./util";
const root = process.cwd();
const p = path.resolve(root, 'build');
const configFile = path.resolve(root, 'config/config.json');
const app = Express();
app.use(Express.static(p));
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.get('/', (req, res) => {
res.sendFile(`${p}/index.html`, {
headers: {
'Content-Type': 'text/html'
}
});
});
app.post('/active', async (req, res) => {
const { active } = req.body;
try {
await writeFile(configFile, JSON.stringify({ active }));
} catch (error) {
throw error;
res.status(500).send(error);
}
res.status(200).send('Ok');
});
app.get('/active', async (req, res) => {
let active;
try {
active = JSON.parse(await readFile(configFile));
} catch (error) {
throw error;
res.status(500).send(error);
}
res.status(200).send(active);
});
app.listen(process.env.PORT, (err) => {
if (err) throw err;
console.log(`Server is running on localhost:${process.env.PORT}`);
});
import fs from "fs";
const readFile = (path, options) => new Promise((resolve, reject) => {
fs.readFile(path, options, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
const writeFile = (path, data, options) => new Promise((resolve, reject) => {
fs.writeFile(path, data, options, (err) => {
if (err) reject(err);
resolve();
});
});
export {
readFile,
writeFile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment