Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Last active March 27, 2017 12:34
Show Gist options
  • Save xgqfrms-GitHub/c1b34a760db12ed50475e3733e6e1c58 to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/c1b34a760db12ed50475e3733e6e1c58 to your computer and use it in GitHub Desktop.

JSON-Async-error

Using Node.JS,read a JSON object?

https://www.npmjs.com/package/jsonfile

Async-json-error

js code

// Read Asynchrously

// D:\NodeJs>node readAsync.js

// Define JSON File
var fs = require("fs");

console.log("***STARTING***\n");

//Get content from file
//ES 5
var contents = fs.readFile('dummy.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log("data =" + data);
});

//ES 6
/*var contents = fs.readFile('dummy.json', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});*/

// Define to JSON type
var jsonContent = JSON.parse(contents);


// Get Value from JSON
console.log("User Name:", jsonContent.username);
console.log("Email:", jsonContent.email);
console.log("Password:", jsonContent.password);

console.log("\n***EXIT***");

json file

{
    "username": "xyz",
    "password": "xyz@123",
    "email": "[email protected]",
    "uid": 1100
}

???

@deep9
Copy link

deep9 commented Nov 3, 2016

The contents of the file is available only after the read is finished, so either use fs.readFileSync, which will return the content, or

fs.readFile('dummy.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log("data =" + data);
    // Define to JSON type
    var jsonContent = JSON.parse(data);


    // Get Value from JSON
    console.log("User Name:", jsonContent.username);
    console.log("Email:", jsonContent.email);
    console.log("Password:", jsonContent.password);

    console.log("\n***EXIT***");
});

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment