stuck in between the code. Please help
User story:
Command line user want to use js script to open a csv file (example attached), and for all the dev_no items (5000+) read from the file execute a shell curl command
| serial_no | type | dev_no | accu_pulses | last_update | warehouse |
|---|---|---|---|---|---|
| 1833002293 | 30 | 4437e68af4e01038 | 10 | 2021-09-08 11:01:20 | false |
Code for executing curl command: Works!
const { stdout } = require('process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const header = 'curl -X GET -k \"XXXX/api/v1/device?id='
const end = '&access_token=XXXX\"'
async function CurlExample(DeviceId) {
const {
stdout,
stderr
} = await exec(header+DeviceId+end);
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
const dev_no= [ "4437e68af4e01027" , ]
for (let i = 0; i < eUID.length; i++) {
CurlExample(eUID[i],stdout)
}
Code for CSV import: used as guidance https://sebhastian.com/javascript-csv-to-array/ works fine, but then I am stuck how to address the correct element of the data array and pass it as argument to the Curl shell command!
Ask: help execute the user story by adding the missing command Extra bonus: propose a better code!
thanks!
kind of figured it out on my own, probably not the most elegant solution out there, due to many imports, but works, as long as there is only one column in the file... Comments and improvements highly welcomed!
const csv = require('csv-parser')
const fs = require('fs')
const util = require('util');
const fileNames = process.argv.splice(2);
const { stdout } = require('process');
const exec = util.promisify(require('child_process').exec);
const header = 'curl -X GET -k \"https://XXXX/api/v1/device?id='
const end = '&access_token=XXXXXX\"'
const results = [];
async function CurlExample(DeviceId) {
const {
stdout,
stderr
} = await exec(header+DeviceId+end);
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
console.log(fileNames)
fs.createReadStream(`${fileNames}`)
//fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
for (let i=0; i < results.length; i++) {
console.log(results[i].dev_eui) ;
CurlExample(results[i].dev_eui, stdout) ;
}
});
to call the script:
$ node <script name> data.csv