Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var fs = require('fs');
- //ES5
- fs.readFile('./test.json', (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");
- }
- }
- })
- //ES6
- function getFileContents(file) {
- return new Promise(
- (resolve, reject) => {
- fs.readFile(file, (err, res) => {
- if(err) {
- reject(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('./test.json')
- .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