Why createReadStream function sending corrupt file? - javascript

I am generating a file from url using fs module to my local system. and it is hopefully success. but when I try to post that file into group using createReadStream() function it is sending me a corrupt file.
Currently I tried with excel file.
function saveFileToLocal(urlData,fileName){
return new Promise ((res,rej) => {
https.get(urlData, function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream(path+`/controller/localmaping/files/${fileName}`)
response.pipe(file);
file.on('finish', function() {
file.close(); // close() is async
});
res('done')
}
else{
rej('failed')
}
})
})
}
async function postAttachmentToGroup(groupid, senderId, text, urlData) {
let fileName = urlData.substring(urlData.lastIndexOf('/') + 1).split("?")[0] // File name
await saveFileToLocal(urlData,fileName)
console.log(fileName)
console.log(path)
request({
url: "https://graph.facebook.com/group_file_revisions",
headers: { "Content-Type": "form-data","Authorization":"Bearer "+config.ACCESS_TOKEN },
method: "POST",
formData:{"file":fs.createReadStream(path+`/controller/localmaping/files/${fileName}`)}
}, (err, res, body) => {
if (!err) {
let id = JSON.parse(body).id;
let request_body = {
"message": text + "\nPost by #[" + senderId + "]",
"formatting":"MARKDOWN",
"files": [ id ]
}
request({
"uri": `https://graph.workplace.com/${groupid}/feed`,
"qs": { "access_token": config.ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log(body)
console.log('Post Success in feed!')
}
else {
console.error("Unable to Post in feed" + err);
}
});
}
else {
console.error("Unable to Post in feed" + err);
}
})
}

I solved this problem by adding callback function. Also added a functionality to delete file from the local storage after successful file sending process.
function postAttachmentToGroup(groupid, senderId, text, urlData) {
let fileName = urlData.substring(urlData.lastIndexOf('/') + 1).split("?")[0]
https.get(urlData, function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream(path+`/controller/localmaping/files/${fileName}`)
response.pipe(file);
file.on('finish', function() {
request({
url: "https://graph.facebook.com/group_file_revisions",
headers: { "Content-Type": "multipart/form-data","Authorization":"Bearer "+config.ACCESS_TOKEN },
method: "POST",
formData:{"file":fs.createReadStream(path+`/controller/localmaping/files/${fileName}`)}
}, (err, res, body) => {
if (!err) {
let id = JSON.parse(body).id;
console.log(id)
let request_body = {
"message": text + "\nPost by #[" + senderId + "]",
"formatting":"MARKDOWN",
"files": [ id ]
}
request({
"uri": `https://graph.workplace.com/${groupid}/feed`,
"qs": { "access_token": config.ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log(body)
console.log('Post Success in feed!')
fs.unlink(path+`/controller/localmaping/files/${fileName}`,function (err){
if(err){
console.log("error in deleting file")
}
else{
console.log("file deleted successfully")
}
})
}
else {
console.error("Unable to Post in feed" + err);
}
});
}
else {
console.error("Unable to Post in feed" + err);
}
})
});
}
else{
console.log('failed')
}
})
}

Related

How to delete a forge bucket from Autodesk forge

I am successfully creating Bucket and uploadFile successfully using sample.
https://github.com/Autodesk-Forge/forge-extensions
I added the delete function
But when I delete the bucket I get an error.
----oss.js---
router.post('/buckets', async (req, res, next) => {
let payload = new PostBucketsPayload();
payload.bucketKey = config.credentials.client_id.toLowerCase() + '-' + req.body.bucketKey;
payload.policyKey = 'transient'; // expires in 24h
try {
// Create a bucket using [BucketsApi](https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/BucketsApi.md#createBucket).
//Bucket createBucket(postBuckets, opts, oauth2client, credentials)
await new BucketsApi().createBucket(payload, {}, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
router.delete('/buckets/delete', async (req, res, next) => {
const encoded_bucketKey = encodeURI(req.bucketKeyID);
try {
// Delete a bucket using
await new BucketsApi().deleteBucket(encoded_bucketKey, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
-----------ForgeTree.js -------
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function deleteBucket() {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
switch (node.type) {
case 'bucket':
jQuery.ajax({
url: '/api/forge/oss/buckets/delete',
type:'delete',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': node.text , 'bucketKeyID' : node.id}),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
},
error: function (err) {
alert('Bucket delete error:')
console.log(err);
}
});
break;
}
console.log("Delete Bucket=%j", node)
}
I checked the config.js in the sample, it doesn't include bucket:delete scope when acquiring the token by default. Have you added the scope in your code?
Also inside delete route,
const encoded_bucketKey = encodeURI(req.bucketKeyID);
should be
const encoded_bucketKey = encodeURI(req.body.bucketKeyID);
Otherwise, you'll have undefined as encoded_bucketKey.

How to extract a parsed email address from a LinkedIn API response?

I'm trying to setup a custom Auth0 LinkedIn Connection.
This is what I have for the Fetch User Profile Script:
function fetchUserProfile(accessToken, context, callback) {
//Create the profile object
const profile = {
user_id: '',
given_name: '',
family_name: '',
email: '',
};
// Call the Linkedin Primary Contact API
request.get(
{
url: 'https://api.linkedin.com/v2/me',
headers: {
'Authorization': 'Bearer ' + accessToken,
}
},
(err, resp, body) => {
if (err) {
return callback(err);
}
if (resp.statusCode !== 200) {
return callback(new Error(body));
}
let bodyParsed;
try {
bodyParsed = JSON.parse(body);
} catch (jsonError) {
return callback(new Error(body));
}
profile.user_id = bodyParsed.id;
profile.given_name = bodyParsed.localizedFirstName;
profile.family_name = bodyParsed.localizedLastName;
}
);
// Call the Linkedin Profile API
request.get(
{
url: 'https://api.linkedin.com/v2/clientAwareMemberHandles?q=members&projection=(elements*(primary,type,handle~))',
headers: {
'Authorization': 'Bearer ' + accessToken,
}
},
(err, resp, body) => {
if (err) {
return callback(err);
}
if (resp.statusCode !== 200) {
return callback(new Error(body));
}
let bodyParsed;
try {
bodyParsed = JSON.parse(body);
} catch (jsonError) {
return callback(new Error(body));
}
console.log(body);
profile.email = bodyParsed.elements.handle~.emailAddress;
}
);
//Send the profile object to the callback
callback(null, profile);
}
It works (almost) but I'm having trouble putting emailAddress into the profile object.
The console.log(body); returns something like this (email redacted):
{
"elements":[
{
"handle":"urn:li:emailAddress:102319820",
"type":"EMAIL",
"handle~":{
"emailAddress":"REDACTED#gmail.com"
},
"primary":true
}
]
}
The problem is that profile.email = bodyParsed.elements.handle~.emailAddress; gives an error because it uses the ~ symbol.
So how do I access emailAddress and insert it into the profile object?

Async/Await Method Issue

I am working on MERN Stack Application(Mean,Express,ReactJS,NodeJS). I have one issue is that I have many more methods in mlcontroller.js page and I call some methods on REST API so I call that methods under that API from mlrouter.js but all that API is Async so currently API takes data slots vise means I give u an example that in one time take 100 data from first method and then pass to another method and pass from all methods again come to first method and take next 100 data and repeat same process again but I need to take all data in one time means untill one method will not complete not move on another method how's that possible with node js?
I place my code here :
mlrouter.js
ensureApiAuthenticated,
authController.checkReadOnlyUser,
mlController.getAPIData,
mlController.getData,
mlController.getCRCDetails,
mlController.getDetails,
mlController.uploadData
)
MlController.js
async function getAPIData(req, res, next) {
try {
let loanboardapi = " ", dealersocket = " ";
loanboardapi = {
url: "https://loanboard.houstondirectauto.com/api/User/GetAuthorizationToken?username=amin#houstondirectauto.com&password=test#123",
method: "GET"
};
dealersocket = {
url: 'https://idms.dealersocket.com/api/authenticate/GetUserAuthorizationToken?username=ankur#houstondirectauto.com&password=H5d465#!ddfdd45dsfd688&InstitutionID=105815',
method: 'GET'
};
request(loanboardapi,
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
loantoken = JSON.parse(body).token;
console.log(loantoken);
});
request(dealersocket,
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
dealertoken = JSON.parse(body).Token;
console.log(dealertoken);
next();
});
}
catch (e) {
req.error = e;
next();
}
}
function getData(req, res, next) {
try {
let result;
request.get('https://idms.dealersocket.com/api/account/getaccountlist?token=' + dealertoken + '&LayoutID=2002313&PageNumber=1&accounttype=i&accountstatus=a,c,b,o,r,s,x',
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
result = JSON.parse(body);
console.log(result);
totalpage = parseInt(result.TotalPages);
let resultdata = Object.assign({}, result.Data);
console.log(resultdata);
//getSSN(totalpage, dealertoken, next);
next();
})
}
catch (e) {
req.error = e;
next();
}
}
async function getCRCDetails(req,res,next) {
async.eachSeries(ssn, async (item) => {
let CBCOptions = {
method: "POST",
url: "https://loanboard.houstondirectauto.com/api/Report",
headers: {
"Content-Type": "application/json",
Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
},
body: JSON.stringify({
token: loantoken,
action: "CBCReport",
variables: {
ssn: item,
},
}),
};
let EMpInfoption = {
method: "POST",
url: "https://loanboard.houstondirectauto.com/api/Report",
headers: {
"Content-Type": "application/json",
Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
},
body: JSON.stringify({
token: loantoken,
action: "getEmployerInfo",
variables: {
ssn: item,
},
}),
};
try {
let resultCBCOptions = await requestpromise(CBCOptions);
let EmployerInfoOptions = await requestpromise(EMpInfoption);
console.log(resultCBCOptions)
console.log(EmployerInfoOptions)
CRCOptions.push(resultCBCOptions);
EmpOption.push(EmployerInfoOptions);
} catch (error) {
console.log(error);
}
},
() => {
next();
}
);
}
async function getDetails(req,res,next) {
for(let i =0;i<CRCOptions.length;i++){
for(let j=0;j<EmpOption.length;j++){
let resdata = JSON.parse(CRCOptions[i]);
console.log(resdata);
result = resdata.data.DigifiResponse;
console.log(result);
let bodydata = JSON.parse(EmpOption[i]).data;
let crcssn = JSON.parse(CRCOptions[i]).ssn;
let empssn = JSON.parse(EmpOption[i]).ssn;
console.log("CRCSSN=",crcssn);
console.log("EMPSSN=",empssn);
if(crcssn == empssn)
{
for(let r=0;r<result.length;r++){
let crcdata = result[r];
console.log(crcdata);
for(let b=0;b<bodydata.length;b++) {
let annual_income;
console.log(bodydata[b]);
let mergedata = Object.assign(crcdata, bodydata[b]);
console.log("merge", mergedata);
if (mergedata["IncomeFrequency"] == "Monthly") {
annual_income = (parseInt(mergedata["Income"]) * 12).toString();
console.log(annual_income);
}
else {
annual_income = mergedata["Income"];
}
let binary = {
"accounts_opened": mergedata["total_number_of_open_accounts"],
"bankruptcies": mergedata["total_number_of_bankruptcies"],
"collections": mergedata["total_number_of_collections"],
"credit_inquiries_last_6_months": mergedata["total_number_of_inquires_in_the_last_6_months"],
"past_due_accounts": mergedata["total_number_of_accounts_currently_past_due"],
"open_accounts": mergedata["total_number_of_open_accounts"],
"high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(binary);
let arraybinary = Object.assign({},binary);
console.log(arraybinary);
binarydata.push(arraybinary);
console.log(binarydata);
let categorical = {
"bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
"credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
"months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
"ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
"number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
"open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
"pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
"total_current_balance": mergedata["total_account_balance"],
"total_high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(categorical);
let arraycategory = Object.assign({},categorical);
console.log(arraycategory);
categoricaldata.push(arraycategory);
let Linear = {
"bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
"credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
"months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
"ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
"number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
"open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
"pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
"total_current_balance": mergedata["total_account_balance"],
"total_high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(Linear);
let arraylinear = Object.assign({},Linear);
console.log(arraylinear);
Lineardata.push(arraylinear);
}
}
}
break;
}
}
console.log(binarydata.length);
console.log(binarydata);
converter.json2csv(binarydata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/binarydata.csv',csv);
console.log('File Written');
})
converter.json2csv(Lineardata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/lineardata.csv',csv);
console.log('File Written');
})
converter.json2csv(categoricaldata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/categorydata.csv',csv);
console.log('File Written');
})
next();
}
async function uploadData(req,res,next){
let moduletype = sessionStorage.getItem('moduletype');
console.log(moduletype);
req.params.id = sessionStorage.getItem('modelid');
console.log(req.params.id);
try {
res.status(200).send({
status: 200,
timeout: 10000,
type: 'success',
text: 'Changes saved successfully!',
successProps: {
successCallback: 'func:window.createNotification',
},
responseCallback: 'func:this.props.reduxRouter.push',
pathname: `/ml/models/${req.params.id}/training/historical_data_${moduletype}`,
});
} catch (e) {
periodic.logger.warn(e.message);
res.status(500).send({ message: 'Error updating model type.', });
}
}```
Cannot understand your question, but I assume you want to get all the async request in one go.
You can achieve this with Promise.all, all the results will be returned as an array, and all the request will run at the same time.
const results = await Promise.all([asyncRequest1, asyncRequest2, asyncRequest3])
getting resulsts sequentially.
await asyncRequest1();
await asyncRequest2();
await asyncRequest3();

When uploading two images, console.log(parsedRes) only returns one object instead of (the expected) two

So, I'm trying to fetch base64 data (urls) from two images I uploaded to the cloud/server, but when I parsed the response, I only get 1 object instead of 2 (i.e. only the url for the first image).
I must be overseeing something fundamentally, but I can't see it. Appreciate the advice.
Can some help explain to me why the code below doesn't work?
[EDIT: I've included the server code. Hopefully this makes it clearer as to the problem I'm facing]
.then(token => {
authToken = token;
return fetch("myappURL/storeImage",
{
method: "POST",
body: JSON.stringify({
image: image.base64,
coverImage: coverImage.base64
}),
headers: { Authorization: "Bearer " + authToken }
});
})
.catch(err => {
console.log(err);
alert("Oops! Something went wrong, please try again1")
dispatch(uiStopLoading());
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw(new Error());
}
})
.then(parsedRes => {console.log(parsedRes)}); // I only get 1 result instead of 2 (why?!)
Server-side code:
exports.storeImage = functions.https.onRequest((request, response) => {
return cors(request, response, () => {....
.then(decodedToken => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({ error: err });
});
const bucket = gcs.bucket("myapp.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/places/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image/jpeg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
return response.status(201).json({ // I get this returned
imageUrl:
"https://firebasestorage.googleapis.com/v0/b/" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid,
imagePath: "/places/" + uuid + ".jpg"
});
} else {
console.log(err);
return response.status(500).json({ error: err });
}
}
);
})
.catch(error => {
console.log("Token is invalid!");
response.status(403).json({error: "Unauthorized"});
})
.then(decodedToken => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-coverImage.jpg", body.coverImage, "base64", err => {
console.log(err);
return response.status(500).json({ error: err });
});
const bucket = gcs.bucket("myapp.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-coverImage.jpg",
{
uploadType: "media",
destination: "/coverPlaces/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "coverImage/jpeg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, coverFile) => {
if (!err) {
return response.status(201).json({ // I do NOT get this returned (why not?!)
coverImageUrl:
"https://firebasestorage.googleapis.com/v0/b/" +
bucket.name +
"/o/" +
encodeURIComponent(coverFile.name) +
"?alt=media&token=" +
uuid,
coverImagePath: "/coverPlaces/" + uuid + ".jpg"
});
} else {
console.log(err);
return response.status(500).json({ error: err });
}
}
);
})
.catch(error => {
console.log("Token is invalid!");
response.status(403).json({error: "Unauthorized"});
});
});
});

nested Async not executing as expected

I am new to node js and I am trying to use async module to eliminate the setTimeouts. Here I am facing a problem. It is not working as expected. It calls the second function even before the first function completes execution. I searched for answers and tried multiple ways. But it doesn't seem to work. It prints "Inside db insert in async series" even before the async.forEach finishes. Can anyone please check the code and tell me where I'm going wrong?
setTimeout(function() {
async.series([function(callback1) {
console.log("Inside async series");
try {
var msg = "";
var datas = [];
for (var i = 0; i < service_name.length; i++) {
console.log("Inside for loop service names");
var child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
console.log("datas array===" + JSON.stringify(datas))
}
async.forEach(datas, function(data1, callback) {
console.log("Inside async task");
var data = JSON.stringify(data1);
console.log("data value===" + JSON.stringify(data));
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances' +
'?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
console.log("options is" + JSON.stringify(options));
var reqst = http.request(options, function(res) {
console.log("Sent for request");
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
console.log("message =======", msg);
console.log("-----------------------------------------");
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
console.log("printing msg--" + msg1);
console.log("-----------------------------------------");
console.log("here i am", i);
console.log(service_name.length - 1);
callback();
} catch (err) {
console.log(err);
}
});
});
reqst.on('error', function(e) {
console.log(e);
});
reqst.write(data);
reqst.end();
}, function(err) {
console.log("for each error" + err);
});
callback1(null, null);
} catch (err) {
console.log(err);
}
},
function(callback1) {
console.log("Inside db insert in async series")
db_insert(service_name, solnName, full_token_new, uname, version);
callback1(null, null);
}
],
function(err, results) {
if (err) {
console.log("There's an error" + err);
} else {
console.log("result of async", results);
}
})
}, 3000)
You are mixing try...catch with asynchronous code, this is bad practice and almost impossible to do right.
Also, your error stem from the fact you are calling callback just after async.forEach, which don't finish, and go to the next step.
Also, what do you mean by "eliminate the timeout"? Your whole code is in it, you can remove it whenever you want.
'use strict';
async.series([
(callback) => {
let msg = "",
datas = [],
i = 0;
while(i < service_name.length) {
let child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
i = i + 1;
}
async.forEach(datas, (data1, callback) => {
let data = JSON.stringify(data1),
options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
},
reqst = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
msg += chunk;
});
res.on('end', () => {
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
callback();
});
});
reqst.on('error', (error) => {
callback(error);
});
reqst.write(data);
reqst.end();
}, (error) => {
callback(error);
});
},
(callback) => {
db_insert(service_name, solnName, full_token_new, uname, version);
callback();
}
],
(error, results) => {
if (error) {
console.log("There's an error" + error);
} else {
console.log("result of async", results);
}
});
Since this smell heavily like a plssendzecode question, I've removed every console.log and gone ES6 to make sure you will not be able to use it as such and need to read the change I made.
I simplify code a little.
datas and processData aren't good names.
setTimeout(onTimer, 3000);
function onTimer() {
var datas = service_name.map(function(name, i) {
return {
space_guid: space_guid,
name: name,
service_plan_guid: service_plan_guid[i]
}
});
function processData(data, callback) {
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
var reqst = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
msg = JSON.parse(msg);
callback(null, msg);
} catch (err) {
callback(err);
}
});
});
reqst.on('error', callback);
reqst.write(JSON.stringify(data));
reqst.end();
}
async.map(datas, processData, function(err, results) {
if (err);
return console.log(err);
// process msg of each request db_insert(...);
});
};

Categories

Resources