Advertisement
Guest User

NODE JS Harmony ES6 vs ES5

a guest
Aug 31st, 2015
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var fs = require('fs');
  2.  
  3. //ES5 way, callbacks.
  4.  
  5. fs.readFile(process.argv[2], (error, text) =>
  6.    {
  7.     if(error) {
  8.         console.error("Error");
  9.     } else {
  10.         try {
  11.             var obj = JSON.parse(text);
  12.             console.log(JSON.stringify(obj, null, 4));
  13.         } catch (e) {
  14.             console.error("Invalid JSON file");
  15.         }
  16.     }
  17. })
  18.  
  19. //Run with "node --harmony [filename] [file.json]"
  20.  
  21. //ES6 way, creating a promise function, then resolving it with '.then' below.
  22.  
  23. function getFileContents(file) {
  24.     return new Promise(
  25.         (resolve, reject) => {
  26.             fs.readFile(file, (err, res) => {
  27.                 if(err) {
  28.                     reject('Invalid File: ' + new Error(this.statusText));
  29.                 } else {
  30.                     try {
  31.                         var obj = JSON.parse(res);
  32.                         var data = JSON.stringify(obj, null, 4);
  33.                         resolve(data);
  34.                     } catch (e){
  35.                         reject("Invalid JSON file")
  36.                     }
  37.                 }
  38.             })
  39.         }
  40.     )
  41.  
  42. }
  43.  
  44.  
  45. getFileContents(process.argv[2])
  46.     .then((value) => {
  47.     console.log("value");
  48.     console.log(value);
  49. },
  50.          (reason) => {
  51.     console.log("error");
  52.     console.log(reason);
  53. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement