Node.js hangs on HTTP get when download files - node.js

I want to download a series of ts files, but every time I run this code, it will be stuck in the download process of a file without any error message.
However, if you put the url in the program in the address bar of the browser, or use a tool like wget, you can still download it.
const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();

const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();
const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MmFmN2JkNzEtODc3Mi00OThmLThjNzQtN2Y5NTQ3ZTgxYjA2IiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzEzNzU4fX19XX0_&Signature=hFOZlf5Iqf7k-LqVms1FT4LKoEM8psMVkCsdjoHGhKztNTzROyGgfHg34RYr3ezffQaQV6drXBuID1NMypQhwSXgJ-ZRAoGC3KnKtrfm9bSpK2Wq97sZf97D5PbBn7wNaJhmfvbztym-cRknztepOqM2v~KvCz6~esS99TOsWbtQFBZWLPacp5MV3v5eZ4wh2WJXX1jDqI1XmpZ0jyU2oJCXOgVbvU1aF86E7duvniDrbhmS1R00~tWTAETBbmBSubDw-7fGq7XzeZcFRfXbdwb0a9KwsAGh54lj1UBUMsDzEtH8vI8r9aC~MnFIRub1KxsFSOzUlRLYRp4GsPJQiQ__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=2af7bd71-8772-498f-8c74-7f9547e81b06';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();

You need to download a file, write it to stream, and then pipe it.
https://nodejs.org/api/https.html#https_https_get_url_options_callback
https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
var https = require('https');
var fs = require('fs');
function doRequest(url, dest) {
return new Promise(function (resolve) {
https.get(url, res => {
let data = '';
res.on('data', (buffer) => {
data += buffer; // save downloaded data
});
res.on('end', () => {
var stream = fs.createWriteStream(dest);
stream.write(data, 'binary');
stream.on('finish', () => {
resolve('File Saved !');
});
res.pipe(stream);
});
}).on('error', function (e) {
reject('re try to get ts ...' + e);
});
});
}
for (let i = 21; i < 100; i++) {
var ts_url =
'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000' +
i +
'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
doRequest(ts_url, i + '.ts')
.then(console.log)
.catch(console.log);
}

Related

How can I Convert code from Nodejs to Angular including API features [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
This post was edited and submitted for review 4 days ago.
Improve this question
I need to convert Nodejs code into Angular. Please suggest me all the steps. I have Nodejs code which is for Get Data using API. That I need to convert into Angular.
I have a task to get Data from Autodesk using their API and Post into MySQL Database (Workbench). This task has already been done in NodeJs. I want to apply same functionality in Angular.
Controller Code : UpdateController.js
const fs = require('fs');
const path = require('path');
const csvtojson = require('csvtojson');
const xlsx = require('xlsx');
const mongoose = require('mongoose');
const openssl = require('openssl-nodejs');
const extract = require('extract-zip');
const SubscriptionsModel = require('../models/subscription');
const PriceListModel = require('../models/pricelist');
const AuthModel = require('../models/auth');
var SubscriptionController = require('../controllers/subscriptioncontroller');
const { sendPasswordNotificationAfterBatch } = require('../models/notification');
var auth = new AuthModel();
class UploadController {
getCSVData(file){
console.log("In getCSVData");
return new Promise((resolve, reject) => {
csvtojson()
.fromFile(file)
.then(csvData => {
//console.log(csvData);
resolve(csvData);
}).catch(err => {
reject(err);
});
});
}
getXLSXData(filename){
console.log("In getXLSData");
return new Promise((resolve, reject) => {
var workbook = xlsx.readFile(filename);
var sheet_list = workbook.SheetNames;
var sheet = workbook.Sheets[sheet_list[0]];
var jsonObjects = xlsx.utils.sheet_to_json(sheet, { range: 7, raw: true, default: null });
var response = [];
response = jsonObjects.filter(item => {
return item.SRP !== undefined && item.SRP !== null && item.DTP !== undefined && item.DTP !== null
});
resolve(response);
}).catch(error => {
throw error;
});
}
updatePricelist(filePath){
return new Promise((resolve, reject) => {
this.getXLSXData(filePath).then(res => {
if(res){
// Delete backup
//PriceListModel.collection.drop();
// Create collection for updated data
PriceListModel.insertMany(res, err => {
if(err){
reject(err);
}
resolve();
})
}
}).catch(error => {
reject(error);
})
});
}
importSubscriptions()
{
console.log("In Import Subscriptions");
var url = `v1/export/subscriptions`;
console.log(`Importing subscription data...`);
return new Promise((resolve,reject) =>{
var body = {
'startDateSince': '2000-01-01'
}
auth.post(url, body).then(function(res)
{
var d = JSON.parse(res);
console.log(d);
resolve(d);
}).catch(err => {
reject(err);
});
});
}
checkImportSubscriptionJobStatus(jobId, count){
var url = `/v1/export/subscriptions/${jobId}`;
console.log(`Checking import subscription job status ${++count}...`);
return new Promise((resolve,reject) =>{
auth.getUsingHttpPlugin(url).then((res) => {
if (res.statusCode == 303) {
console.log("Current status is " + res.statusCode);
resolve(res.headers["location"]);
}
else {
console.log(`Current status is ${res.statusCode}, will retry in 60 seconds again `);
setTimeout(() => {
this.checkImportSubscriptionJobStatus(jobId, count).then(fileUrl => {
resolve(fileUrl);
});
}, '60000');
}
}).catch(function(err){
reject(err);
});
});
}
downloadFile(jobId, fileUrl) {
console.log("Downloading file...");
return new Promise((resolve, reject) => {
var file = fs.createWriteStream(`uploads/subscriptions/${jobId}.csv.zip.enc`);
//console.log(file);
console.log(fileUrl);
auth.getPlainHttp(fileUrl).then(function (response) {
response.pipe(file);
console.log(file.path);
resolve();
}).catch(err => {
console.log("In Catch");
reject(err);
});
});
}
decriptFieUsingOpenSSL(fileName, password) {
console.log("Decrypting file...");
return new Promise((resolve, reject) => {
var encFile = `../uploads/subscriptions/${fileName}.zip.enc`;
var zipFile = `../uploads/subscriptions/${fileName}.zip`;
var openSSLCmd = `enc -aes-256-cbc -md sha512 -d -in ${encFile} -out ${zipFile} -k ${password}`;
console.log('start running openssl command ' + openSSLCmd);
setTimeout(function () {
openssl(openSSLCmd, () => {
resolve();
})
}, 5000);
});
}
updateSubscriptionData(){
return new Promise((resolve, reject) => {
this.importSubscriptions().then(response => {
if(response.error !== undefined){
console.log(`Error Code: ${response.error.code}`);
console.log(`Message: ${response.error.message}`);
reject();
}else{
var id = response.id;
var password = response.password;
this.checkImportSubscriptionJobStatus(id, 0).then(fileUrl => {
this.downloadFile(id, fileUrl).then(() => {
var fileName = `${id}.csv`;
this.decriptFieUsingOpenSSL(fileName, password).then(() => {
console.log("File decrypted successfully...");
var targetFolder = path.join(__dirname, '..', 'uploads', 'subscriptions');
var zipFile = path.join(targetFolder, `${fileName}.zip`);
extract(zipFile, { dir : targetFolder }).then(() => {
console.log("Extracted file successfully");
var fullFileName = path.join(targetFolder, fileName);
this.getCSVData(fullFileName).then(res => {
if(res){
SubscriptionController.updateSubscriptions(res).then(data => {
resolve('Subscriptions data replicated successfully!!!');
console.log("CHECK NOTIFICATION");
sendPasswordNotificationAfterBatch();
}).catch(err => {
throw err;
});
}
}).catch(error => {
reject(error);
})
})
});
});
});
}
}).catch(err => {
reject(err);
})
});
}
}
module.exports = new UploadController();
Model Code : auth.js
var CryptoJS = require("crypto-js");
var request = require("request");
var httpRequest = require("http");
var httpsRequest = require("https");
var config = require('../config.json');
class AuthModel {
constructor() {
this.timestamp = Math.floor((new Date()).getTime() / 1000);
this.consumer_key = config.app.consmer_key;
this.consumer_secret = config.app.consumer_secret;
this.callback_url = config.app.callback_url;
this.partner_csn = config.app.partner_csn;
this.environment_url_stg = "enterprise-api-stg.autodesk.com"; //STG Environment
this.environment_url_prd = "enterprise-api.autodesk.com"; //prd Environment
this.access_token = '';
this.api_timestamp = '';
}
getbaseUrl()
{
var env = config && config.app.env;
console.log("ENVIRONMENT");
console.log(env);
if(env == 'prd')
{
return this.environment_url_prd;
console.log("ENVIRONMENT URL PID");
console.log(this.environment_url_prd);
}
else{
return this.environment_url_stg;
console.log("ENVRIONMENT URL STG");
console.log(this.environment_url_stg);
}
}
get(url, headerData){
var self = this;
return new Promise((resolve, reject) =>{
self.getAccessToken().then(function(token){
var time = Math.floor(Date.now() / 1000);
var header = {
'CSN': self.partner_csn,
'signature': self.getAPISignature(token),
'timestamp': self.api_timestamp,
'Authorization': "Bearer " + token
};
var options = {
method: 'GET',
url: `https://${ self.getbaseUrl() }/${url}`,
headers:header
};
request(options, function (error, response, body) {
if (error) {
reject(error);
}
resolve(body);
});
}).catch(function(err){
reject(err);
});
});
}
post(url, body){
console.log(url);
var self = this;
return new Promise((resolve, reject) =>{
self.getAccessToken().then(function(token){
var time = Math.floor(Date.now() / 1000);
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`,
'signature': self.getAPISignature(token),
'timestamp': self.api_timestamp,
'CSN': self.partner_csn
};
var options = {
method: 'POST',
url: `https://${ self.getbaseUrl() }/${url}`,
headers,
form: body
};
request(options, function (error, response) {
if (error){
reject(error);
}
resolve(response.body);
});
}).catch(function(err){
reject(err);
});
});
}
getAPISignature(token)
{
this.api_timestamp = Math.floor(Date.now() / 1000);
var message = this.callback_url + token + this.api_timestamp;
var hash = CryptoJS.HmacSHA256(message, this.consumer_secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64;
}
createSignature(time)
{
var message = this.callback_url + this.consumer_key + time;
console.log(message);
var hash = CryptoJS.HmacSHA256(message, this.consumer_secret);
console.log(this.consumer_key);
console.log(this.consumer_secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64;
}
createAuthorization(){
var passwordSignature = this.consumer_key + ":" + this.consumer_secret;
console.log(passwordSignature);
var authorization = Buffer.from(passwordSignature).toString('base64')
console.log("Authorization");
console.log(authorization);
return "Basic " + authorization;
}
getAccessToken(){
console.log("IN GetAccessToken");
var self = this;
var time = Math.floor((new Date()).getTime() / 1000);
return new Promise((resolve, reject) =>{
var options = {
method: 'POST',
url:`https://${self.getbaseUrl()}/v2/oauth/generateaccesstoken?grant_type=client_credentials`,
headers: {
timestamp: time,
signature: self.createSignature(time),
Authorization : self.createAuthorization()
}
};
request(options, function (error, response, body) {
if (error) {
reject(error);
}
resolve(JSON.parse(body).access_token);
console.log(JSON.parse(body).access_token);
});
});
}
getUsingHttpPlugin(url, headerData) {
var self = this;
return new Promise((resolve, reject) => {
self.getAccessToken().then(function (token) {
console.log("Get Access Token");
console.log(token);
var time = Math.floor(Date.now() / 1000);
var header = {
'CSN': self.partner_csn,
'signature': self.getAPISignature(token),
'timestamp': self.api_timestamp,
'Authorization': "Bearer " + token
};
var options = {
method: 'GET',
host: `${self.getbaseUrl()}`,
path: `${url}`,
headers: header
};
var s = httpRequest.request(options, (res) => {
resolve(res);
});
s.end();
}).catch(function (err) {
reject(err);
});
});
}
getPlainHttp(url) {
console.log("URL");
console.log(url);
return new Promise((resolve, reject) => {
console.log("In 1");
var s = httpsRequest.get(url, (res) => {
console.log("RESPONSE STATUS CODE");
console.log(res.statusCode);
if (res.statusCode > 200) {
reject(res);
}
resolve(res);
})
s.end();
});
}
}
module.exports = AuthModel;
If any other Node code needed from my side, I am happy to share.

How to download file from gitlab synchronously using NodeJS

I need to download a file from a private gitlab server and I need the method to be synchronous. This was by previous async code and it works fine because I was using promises. But I'm having trouble converting it to synchronous. The other posts i've seen on SO either ended up using async code or didn't have options for headers.
const https = require('https');
const fs = require('fs');
const gitlabUrl = 'https://gitlab.custom.private.com';
const gitlabAcessToken = 'xmyPrivateTokenx';
const gLfilePath = '/api/v4/projects/1234/repository/files/FolderOne%2Ftest.txt/raw?ref=main';
const gLfileName='test.txt';
function downloadFileFromGitlab(filePath, fileName) {
return new Promise((resolve, reject) => {
var options = {
path: filePath,
headers: {
'PRIVATE-TOKEN': gitlabAccessToken
}
};
var url = gitlabUrl
var file = fs.createWriteStream(fileName);
const request = https.get(url, options, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
file.on('error', (err) => {
file.close();
reject(err);
});
});
request.on('error', error => {
throw console.error(error);
});
});
}
downloadFileFromGitlab(gLfilePath,gLfileName);
I was able to figure it out using curl
function downloadFileFromGitlab(filePath, fileName) {
let curlCommand = "curl -s " + gitlabUrl + filePath + " -H 'PRIVATE-TOKEN:" + gitlabAccessToken +"'";
let file = child_process.execSync(curlCommand);
fse.writeFileSync(fileName,file);
}

Return result from python script in Node JS child process

Im trying to return the value from a python script from a nodejs child process and i just cant seem to get it to work, it prints in the console using console.log correctly as it should but only returns undefined, i was wondering if there is a way to directly return that value, or to parse the console.log results into a string.
var sys = require('util');
module.exports = function() {
this.getPlay = function getPlaylist(name) {
const childPython = spawn('python' ,['main.py', name]);
var result = '';
childPython.stdout.on(`data` , (data) => {
result += data.toString();
});
childPython.on('exit' , () => {
console.log(result);
});
}};
Python script is empty for now and prints "Hello 'name' "
Edit:
I tried to use promises and here is what i have:
(async function(){
function test(name) {
return new Promise((resolve , reject) => {
const childPython = spawn('python' ,['main.py', "He"]);
var result = '';
childPython.stdout.on(`data` , (data) => {
result += data.toString();
});
childPython.on('close' , function(code) {
t = result
resolve(result)
});
childPython.on('error' , function(err){
reject(err)
});
})};
var t;
await test(name);
console.log(t);
return t;
})();
Define it like this.
function getPlaylist(name) {
return new Promise((resolve , reject) => {
const childPython = spawn('python' ,['main.py', name]);
var result = '';
childPython.stdout.on(`data` , (data) => {
result += data.toString();
});
childPython.on('close' , function(code) {
resolve(result)
});
childPython.on('error' , function(err){
reject(err)
});
})
};
Remeber to use try...catch for it it gets rejected. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
async function runTest() {
try {
const playList = await getPlaylist();
console.log(playList);
} catch (err) {
}
}
runTest()
const {spawn} = require('child_process');
const getPythonScriptStdout = (pythonScriptPath) => {
const python = spawn('python', [pythonScriptPath]);
return new Promise((resolve, reject) => {
let result = ""
python.stdout.on('data', (data) => {
result += data
});
python.on('close', () => {
resolve(result)
});
python.on('error', (err) => {
reject(err)
});
})
}
getPythonScriptStdout('./python.py').then((output) => {
console.log(output)
})
python.py file
print("hi from python")

Synchronous/sequential REST calls in loop

I'm trying to call a REST API in a "for" loop, however, the results aren't what I'm expecting.
I've attempted to wrap everything in a promise, but the order of operations is still off, executing it asynchronously rather than synchronously.
var https = require('https');
var zlib = require("zlib");
var axios = require('axios');
const cheerio = require('cheerio');
var page = 1;
var hasMore = "true";
function delay() {
return new Promise(resolve => setTimeout(resolve, 300));
}
async function getLocation(page) {
// notice that we can await a function
// that returns a promise
await delay();
var apiUrl = 'https://my.api.com/search/advanced?page=' + page +
'&pagesize=5';
https.get(apiUrl, function(response) {
console.log("headers: ", response.headers);
console.log(response.statusCode)
if (response.statusCode == 200) {
var gunzip = zlib.createGunzip();
var jsonString = '';
response.pipe(gunzip);
gunzip.on('data', function(chunk) {
jsonString += chunk;
});
gunzip.on('end', function() {
obj = JSON.parse(jsonString);
var url = obj.items[0].owner.link;
axios(url)
.then(response => {
const html = response.data;
const $ = cheerio.load(html);
//OUTPUT LOCATION
console.log($('h3.location').text().trim());
})
.catch(console.error);
});
gunzip.on('error', function(e) {
console.log(e);
});
} else {
console.log("Error");
}
});
}
async function startGetLocation() {
var page = 1;
var hasMore = "true";
do {
//OUTPUT PAGE NUMBER
console.log(page.toString());
await getLocation(page);
page = page + 1;
} while (page < 3);
}
startGetLocation();
Based on the sample code, I would have expected the below to output:
1
New York
2
However, it's outputting:
1
2
New York
The problem is that the callback function that you passed to the https.get() function gets executed asynchronously and that the getLocation function does not wait until this part resolves.
So you could simply wrap the https.get() call and the unzipping part in a promise, wait for it to resolve and then do the axios-part.
async function getLocation(page) {
await delay();
var apiUrl = 'https://my.api.com/search/advanced?page=' + page +
'&pagesize=5';
const fetchAndUnzipPromise = new Promise((resolve, reject) => {
https.get(apiUrl, function (response) {
console.log("headers: ", response.headers);
console.log(response.statusCode)
if (response.statusCode == 200) {
var gunzip = zlib.createGunzip();
var jsonString = '';
response.pipe(gunzip);
gunzip.on('data', function (chunk) {
jsonString += chunk;
});
gunzip.on('end', function () {
obj = JSON.parse(jsonString);
var url = obj.items[0].owner.link;
resolve(url);
});
gunzip.on('error', function (e) {
reject(e);
});
} else {
reject(new Error("Statuscode not as exepcted"));
}
});
});
return fetchAndUnzipPromise.then(url => {
return axios(url)
.then(response => {
const html = response.data;
const $ = cheerio.load(html);
//OUTPUT LOCATION
console.log($('h3.location').text().trim());
})
.catch(console.error);
})
}

How to merge two csv files rows in node js

I have 2 csv files which have different different data but having a same header
eg. FILE 1 data is
"CODE","NAME","SUB_USER","SCORE"
"01","TEST","1","5"
"01","TEST","2","6"
other file FILE2 have data like this
"CODE","NAME","SUB_USER","SCORE"
"02","TEST2","3","5"
"02","TEST2","4","6"
so i want to merge both file create FILE3 output like this
"CODE","NAME","SUB_USER","SCORE"
"01","TEST","1","5"
"01","TEST","2","6"
"02","TEST2","3","5"
"02","TEST2","4","6"
I have tried below code
var express = require('express');
var router = express.Router();
var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');
var csv = require("fast-csv");
var file1 = appRoot + '\\csvFiles\\details1.csv';
var file2 = appRoot + '\\csvFiles\\details2.csv';
var stream = fs.createReadStream(file1);
var stream2 = fs.createReadStream(file2);
var fileData1 = [],
fileData2 = [];
csv
.fromStream(stream)
.on("data", function(data) {
fileData1.push(data);
})
.on("end", function() {
console.log("done");
});
csv
.fromStream(stream2)
.on("data", function(data) {
fileData2.push(data);
})
.on("end", function() {
console.log("done");
});
var fileData3 = fileData1.concat(fileData2);
csv.writeToPath("outputfile.csv", fileData3).on("finish", function() {
console.log("END");
});
But not working don't know why?? Please help me
///**********************************************************************//
Thax for help but i got new problem here
After some changes above code start working
var file1 = appRoot + '\\csvFiles\\details1.csv';
var file2 = appRoot + '\\csvFiles\\idetails2.csv';
var stream = fs.createReadStream(file1);
var stream2 = fs.createReadStream(file2);
var fileData1 = [],
fileData2 = [],
i = 0;
csv.fromStream(stream).on("data", function(data) {
fileData1.push(data);
}).on("end", function() {
csv.fromStream(stream2).on("data", function(data) {
if (i != 0) {
fileData2.push(data);
}
i++;
}).on("end", function() {
console.log("done");
var fileData3 = fileData1.concat(fileData2);
csv.writeToPath("outputfile.csv", fileData3).on("finish", function() {
res.send('Done merge');
});
});
});
But problem is that what if my number of file increase then how i will handle that thing
The biggest problem here is a quite common one. You do async tasks but you don't wait for them to finish before you are using their result.
You concat the file data before the "end" callback for each tasks was called.
The solution is to wait for every callback to be called and THEN working with the data.
I created a small example using Promises
const file1 = 'one.csv';
const file2 = 'two.csv';
const stream = fs.createReadStream(file1);
const stream2 = fs.createReadStream(file2);
const fileData1 = [];
const fileData2 = [];
const file1Promise = new Promise((resolve) => {
csv
.parseFile(file1, {headers: true})
.on('data', function(data) {
fileData1.push(data);
})
.on('end', function() {
console.log('done');
resolve();
});
});
const file2Promise = new Promise((resolve) => {
csv
.parseFile(file2, {headers: true})
.on('data', function(data) {
fileData2.push(data);
})
.on('end', function() {
console.log('done');
resolve();
});
});
Promise.all([
file1Promise,
file2Promise,
])
.then(() => {
const fileData3 = fileData1.concat(fileData2);
console.log(fileData3);
const csvStream = csv.format({headers: true});
const writableStream = fs.createWriteStream('outputfile.csv');
writableStream.on('finish', function() {
console.log('DONE!');
});
csvStream.pipe(writableStream);
fileData3.forEach((data) => {
csvStream.write(data);
});
csvStream.end();
});
I created a function with which you can easily merge multiple files:
function concatCSVAndOutput(csvFilePaths, outputFilePath) {
const promises = csvFilePaths.map((path) => {
return new Promise((resolve) => {
const dataArray = [];
return csv
.parseFile(path, {headers: true})
.on('data', function(data) {
dataArray.push(data);
})
.on('end', function() {
resolve(dataArray);
});
});
});
return Promise.all(promises)
.then((results) => {
const csvStream = csv.format({headers: true});
const writableStream = fs.createWriteStream(outputFilePath);
writableStream.on('finish', function() {
console.log('DONE!');
});
csvStream.pipe(writableStream);
results.forEach((result) => {
result.forEach((data) => {
csvStream.write(data);
});
});
csvStream.end();
});
}
example usage
concatCSVAndOutput(['one.csv', 'two.csv'], 'outputfile.csv')
.then(() => ...doStuff);

Resources