Node.js Showing JSON File in the Browser - json

Using node.js I am attempting to load a .json file (file) and have it viewed on a web browser. So far I have been able to create a JSON object (obj) and viewed the JSON string of that object on the web browser. However, when I attempt to load the file I get the file link and not the file itself. Below is the code:
var jf = require('jsonfile');
var jsonfn = function(request, response) {
var file = '/home/ubuntu/public/json/foods.json';
var obj = {name: 'JP'};
jf.writeFile(file, obj, function(err) {
console.log(util.inspect(jf.readFileSync(file)));
})
response.json(obj);
};
Can anyone provide advice for me being able to load a JSON file and create a response to allow me to view the file in the web browser?

jf.readFile(file, function(err, obj) {
if (err) return response.send(500);
response.json(obj);
});
// or ...
require('fs').readFile(file, function(err, data) {
if (err) return response.send(500);
response.setHeader('Content-Type', 'application/json');
response.send(data);
});

Related

Automated response download (json) Postman

Is it possible to create a Collection in Postman that executes a few hundred requests to an API and download all responses in json?
If it is possible, how to do that?
If it is not possible, what available tools do we have ? (free and open source)
You can use Newman as a library and the NodeJS fs module to do this:
const newman = require('newman'),
fs = require('fs');
newman.run({
collection: '<Collection File Or Link>'
}).on('request', (err, args) => {
fs.writeFile(`./${args.item.name}.json`, args.response.stream, (err) => {
if (err) {
console.error(err);
}
});
});
This will run all the results in your Collection and then save each of the responses to a JSON file. The filename will be the name of the request.

How to read json file on disk using sails js api controller?

I am new to sails js, I have to read json file in a sails generated controller and process the data in it. If its, express I generally use jsonfile module like this in app.js
let jsonfile = require('jsonfile')
let file = '/tmp/data.json'
jsonfile.readFile(file, function(err, obj) {
console.dir(obj)
})
How to do the same in sails js controller?
Oh, It seems as same as in express. I just tried able to read the data like this. In my controller
module.exports = {
readJsonFile: function (req, res) {
const jsonfile = require('jsonfile');
var file = './assets/json/data.json';
jsonfile.readFile(file, function (err, obj) {
if (err) {
res.json({err: err});
}
console.dir(obj)
res.json({obj: obj});
})
}
};
and its working. Thanks.
You can also use the readFileSync to read the JSON file
module.exports = {
index: async function (req, res) {
var filePath = './data/students.json';
let rawdata = fs.readFileSync(filePath);
let data = JSON.parse(rawdata);
sails.log("data", data);
return res.view('pages/index.ejs', data);
},
};

NodeJS Failing to load in credentials file AWS

This is what my code looks like:
'use strict';
process.env.AWS_PROFILE
// Load the AWS SDK for Node.js
const AWS = require('aws-sdk');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
// Load credentials and set region from JSON file
AWS.config.loadFromPath('/Users/testuser/.aws/credentials');
// Load in security group parameters
const securityParams = require('./securityParams.json');
module.exports = {
//Exports creation of Security Groups
CreateSecurityGroup: (req, res) => {
ec2.createSecurityGroup(securityParams, function(err, data) {
if (err) {
return (console.log("Error", err));
}
// Pass the Json as a parameter in this function
ec2.authorizeSecurityGroupIngress(securityParams, function(err, data) {
if (err) {
res.serverError(err, err.stack);
} else {
res.ok(data);
console.log('Ingress Security Rules Created');
}
})
// Pass the Json as a parameter in this function
ec2.authorizeSecurityGroupEgress(securityParams, function(err, data) {
if (err) {
res.serverError(err, err.stack);
} else {
res.ok(data);
console.log('Egress Security Rules Created');
}
})
})
}
}
I'm trying to have the script load configurations from two files; one aws credentials file, and one json. However its throwing errors on the credentials file which looks like this:
[default]
aws_access_key_id=**************
aws_secret_access_key**************
I'm not sure what I'm missing to get it to read the properties in correctly.
Here is the error I'm seeing:
undefined:1
[default]
^
SyntaxError: Unexpected token d in JSON at position 1
at JSON.parse (<anonymous>)
credentials is a plain Ascii file, it's not json file
// Load credentials and set region from JSON file
AWS.config.loadFromPath('/Users/testuser/.aws/credentials');
You can check file type with command file /Users/testuser/.aws/credentials
sample snippet to read props file and set AWS config
var PropertiesReader = require('properties-reader');
var AWS = require('aws-sdk')
var properties = PropertiesReader('/Users/username/.aws/credentials');
AWS.config.update({
accessKeyId : properties.get('aws_access_key_id'),
secretAccessKey : properties.get('aws_secret_access_key'),
region : 'us-west-2'
})
console.log(AWS.config)
Ref:https://www.npmjs.com/package/properties-reader

Node/Express: Trying to send static JSON file to API endpoint

I am working on a MEAN stack app, and I'm trying to create a couple of API endpoints that the Angular client can $http.get, with simple JSON files populated with dummy data.
Here's the orders.json file I'm trying to test it with:
[
{
"order_status":"Shipped",
"order_qty":30
},
{
"order_status":"Shipped",
"order_qty":6
}
]
For example, the api route to $http.get:
apiRouter.get('/:fileName', queries.getStaticJSONFileForDevelopment);
But when I try to use express's sendFile method with a local .json file, like orders.json:
queries.js:
exports.getStaticJSONFile = function(req, res) {
var fileName = req.params.fileName;
console.log('path: ' + path.normalize(__dirname + '/' + fileName));
res.sendFile(path.normalize(__dirname + '/' + fileName), function(err) {
if (err) return res.send({ reason:error.toString() });
});
};
The console.log tells me I'm pointed at the correct path to the file, but Postman delivers this error:
TypeError: undefined is not a function
at Object.exports.getStaticJSONFile [as handle] (path/to/queries.js:260:7)
// queries.js:260:7 points to the 's' in 'sendFile' above
However, when I just send the json data by itself:
res.send([{"order_status":"Shipped","order_qty":30},{"order_status":"Shipped","order_qty":6}]);
...the endpoint renders the data as you would expect. Am I trying to get the sendFile method to do something it's not meant to do, or is there something I'm missing? Thanks very much for any advice you may have!
If You want to read json file and response with json so You can try this:
var jsonfile = require('jsonfile');
exports.getStaticJSONFile = function(req, res) {
var fileName = req.params.fileName;
var file = path.normalize(__dirname + '/' + fileName);
console.log('path: ' + file);
jsonfile.readFile(file, function(err, obj) {
if(err) {
res.json({status: 'error', reason: err.toString()});
return;
}
res.json(obj);
});
};

how to print json array in html return by node.js

i return the array from node.js
reading xml content from txt file and store in array send to html page using ajax method how do this task.
xml2js = require('xml2js');
fs = require('fs');
var arr={};
var parser = new xml2js.Parser();
fs.readFile('D:/test.txt', function(err, data) {
parser.parseString(data, function (err, result) {
arr=result.Cluster.Array[0].String;
});
});
app.get('/test', function(req, res, next) {
res.json({ message: arr }); //passing array data
});
how to display in html page current i used. But i get whole data in console log not able to display in html page get message undefined :
$.ajax({
url: '/test',
complete: function(data) {
JSON.stringify(data);
console.log(data.message);
// document.write(data.message);
for(i=0;i<data.length;i++)
{
document.write(data.message[i].Val);
$('#did').append('<h1>'+data.message[i].Name+'</h1>');
}
}
use a ReadStream, and stream it into your httpResponse
stream = fs.createReadStream "path/to/file.json"
stream.pipe(res)