I have written the codes below to enable Firebase Functions to download a file from the web based on a URL path which I have specified. I didn't manage to get the code below to work as Firebase Function would fail with 503 error status with the message "Service Temporarily Unavailable". Is there a proper way to handle this?
function funcDownloadFile(urlToDownload, cb) {
const sendReq = request.get(urlToDownload);
// Verify response
sendReq.on('response', function(response) {
if (response.statusCode !== 200) {
console.log("Error in download response.statusCode:"+ response.statusCode);
console.log("Error in download response.statusMessage:"+ response.statusMessage);
return cb('Response status was ' + response.statusCode);
}
});
}
Related
I want to call a Node-RED flow from IBM Cloud Functions.
const https = require('https');
function main(params) {
const path = "/" + params.route + "?" + params.query_params ;
const options = {
hostname: params.hostname,
path: path,
port: 443,
method: 'GET'
};
return new Promise((resolve, reject) => {
https.get(options, (resp) => {
resp.on('data', (d) => {
let s = d.toString();
obj = JSON.parse(s);
resolve({ "gw_result": obj })
});
});
})
}
In the Node-RED flow I'm using a HTTP request to get data from another server. For test purposes I used a GET request to google.com but have same results using another Node-RED endpoint.
As soon as I invoke the web action I get the error message "The action did not produce a valid response and exited unexpectedly". The output of the Node-RED flow appears some seconds later in the web action's log although the Node-RED flow works properly and promptly (I used debug Node-RED debug nodes to check this).
The https GET request to Node-RED works well when I replace the http request in Node-RED by something else, e.g. a Function node, even when I use a Delay node to delay the response for a second or so.
This code works, although google.com does not return an object, of course.
var rp = require('request-promise');
function main(params) {
var uri = params.hostname + params.route + params.query_params
return new Promise(function (resolve, reject) {
rp(uri)
.then(function (parsedBody) {
obj = JSON.parse(parsedBody);
resolve({ "gw_result": obj
});
})
.catch(function (err) {
resolve({ message: 'failed!!', error: err.toString() });
});
});
}
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
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);
});
};
I have a JSON file that is working properly locally but when I load it from server then it give me error that file is not found.
Here's my gist:
var app=angular.module('starter', ['ionic', 'ui.router']);
app.controller('linksCtrl', function ($scope,$http) {
$http.get("papers.com.pk/API/api/json_files/03-08-2015.json")
.success(function (response) {
$scope.ads = response;
});
});
I wish to get some currency prices from a web service which provides them in JSON format.
Here is the code I am using with the simple example (hello world) -
if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to webserve.";
};
Template.hello.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
Meteor.call('getprice');
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.methods({
getprice: function() {
console.log('On the server');
var url = "http://quotes.instaforex.com/get_quotes.php?m=json&q=AUDUSD";
//var url ="http://www.google.com";
HTTP.get(url, function(error, result) {
if(!error) {
console.log(result.content);
}
else console.log(error);
});
}
});
}
When I run the app, and click the button in the client, i get a timeout message on the server.
Notice the url - If I copy/paste it in a browser I receive the right json,
Cross Domain policy does not apply because the code is on server side.
Any ideas?
Copying into a new project helped, no change required.