Advertisement
beelzebielsk

count-server-promise.js

Nov 19th, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const bp = require('body-parser');
  3. const fs = require('fs');
  4. const app = express();
  5. const counterFile = 'counter.json';
  6.  
  7. // Setting these causes express to use body-parser on your behalf. You
  8. // do not personally use body-parser from here on in.
  9. app.use(bp.urlencoded({
  10.     extended: false
  11. }))
  12. app.use(bp.json());
  13.  
  14. /* When you try to read a file that does not exist, then an error
  15.  * happens. That error is reported to you as an object in the `err`
  16.  * parameter of the readFile callback. One of the properties of this
  17.  * object is 'code', which represents the error code. When the file
  18.  * does not exist, the error code is "ENOENT".
  19.  *
  20.  * I know this because I let the code run without checking for this
  21.  * condition (and without a counter file, to make sure the error
  22.  * happened) and just looked at the error that was printed out.  
  23.  *
  24.  * You might wonder why I turned this into a function, since it is so
  25.  * short. For documentation, honestly. It's easier than writing in
  26.  * comments as to what the wrapped code means whenever I use it.
  27.  */
  28. function isFileNotExistfileErr(fileErr) {
  29.     return fileErr.code === "ENOENT";
  30. }
  31.  
  32. function readFilePromise(path, encoding) {
  33.     return new Promise((resolve, reject) => {
  34.         fs.readFile(path, encoding, (err, data) => {
  35.             if (err)
  36.                 reject(err);
  37.             else
  38.                 resolve(data);
  39.         });
  40.     });
  41. }
  42. function writeFilePromise(path, content) {
  43.     return new Promise((resolve, reject) => {
  44.         fs.writeFile(path, content, (err) => {
  45.             if (err)
  46.                 reject(err);
  47.             else
  48.                 resolve();
  49.         });
  50.     });
  51. }
  52.  
  53. app.get('/', (req, res) => {
  54.     readFilePromise(counterFile, 'utf8')
  55.     .catch(err => {
  56.         if (isFileNotExistfileErr(err))
  57.             return '{"counter" : 0}';
  58.         else {
  59.             res.statusCode = 500;
  60.             res.end();
  61.             console.error("Read Error:");
  62.             console.error(err);
  63.         }
  64.     })
  65.     .then(data => {
  66.         let obj = JSON.parse(data);
  67.         obj.counter++;
  68.         return writeFilePromise(counterFile, JSON.stringify(obj));
  69.     })
  70.     .then(() => {
  71.         res.send("Welcome to my site!");
  72.     })
  73.     .catch(err => {
  74.         res.statusCode = 500;
  75.         res.end();
  76.         console.error("Write Error:");
  77.         console.error(err);
  78.     });
  79. });
  80.  
  81. app.post('/reset', (req, res) => {
  82.     let obj = { counter: 0 };
  83.     writeFilePromise(counterFile, JSON.stringify(obj))
  84.     .then(() => {
  85.         res.send("Okay counter is reset to 0");
  86.     })
  87.     .catch(err => {
  88.         res.statusCode = 500;
  89.         res.end();
  90.         console.error("Write Error:");
  91.         console.error(err);
  92.     });
  93. });
  94.  
  95. app.listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement