Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var fs = require('fs');
- //ES5 way, callbacks.
- fs.readFile(process.argv[2], (error, text) =>
- {
- if(error) {
- console.error("Error");
- } else {
- try {
- var obj = JSON.parse(text);
- console.log(JSON.stringify(obj, null, 4));
- } catch (e) {
- console.error("Invalid JSON file");
- }
- }
- })
- //Run with "node --harmony [filename] [file.json]"
- //ES6 way, creating a promise function, then resolving it with '.then' below.
- function getFileContents(file) {
- return new Promise(
- (resolve, reject) => {
- fs.readFile(file, (err, res) => {
- if(err) {
- reject('Invalid File: ' + new Error(this.statusText));
- } else {
- try {
- var obj = JSON.parse(res);
- var data = JSON.stringify(obj, null, 4);
- resolve(data);
- } catch (e){
- reject("Invalid JSON file")
- }
- }
- })
- }
- )
- }
- getFileContents(process.argv[2])
- .then((value) => {
- console.log("value");
- console.log(value);
- },
- (reason) => {
- console.log("error");
- console.log(reason);
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement