1

I am relatively new to this and haven't quite got my head round how this all works...

Basically I am using the csvtojson function to convert a csv file into json. This works fine and outputs the json array to the console.log.

After performing this action I want to take the json array returned and do some extra things to it e.g outputting to a file.

My question is how do use the array outside of the function where it is created, Alternatively should I be writing the code within the function?

This is my code:

const csvFilePath='./test.csv'
const csv=require('csvtojson')

csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
//should I write code here 
});


console.log(jsonObj);
//This returns jsonObj is not defined
//how do I/Can I read jsonObj here

Can someone help me understand what I need to do here please?

Ryan Howard
  • 21
  • 1
  • 6
  • "Alternatively should I be writing the code within the function?" Yes, if you're using the variable like setting state with it or console logging it. it should be within the .then() callback – Matt Pengelly Jun 22 '18 at 14:48
  • get your `jsonObj` and convert it to an array if it's not already. Then just use javascript to `push()` items to it, then just `write` to the file again. – ZombieChowder Jun 22 '18 at 14:51

1 Answers1

0

Because csv() function is asynchronous and returns a Promise object. You can read the value inside of the .then() function.


How the interpretor sees the code :

// Create a variable and store a data inside
const csvFilePath='./test.csv'

// Create a variable and store a data inside
const csv=require('csvtojson')

// Call the function csv().fromFile(csvFilePath), because it's asynchronous
// deal with the result later
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
});

// Display the content of the variable jsonObj
// jsonObj is not declared, display 'undefined'
console.log(jsonObj);

// Leave the current function

after some time

// Execute the .then function
.then((jsonObj)=>{
   // Display the content of the variable jsonObj
   console.log(jsonObj);
});

Here is a demonstrating snippet

const asynchronousFunction = () => new Promise((resolve) =>
  setTimeout(() => resolve('asynchronous'), 1000));

const ret = 'not initialized';

asynchronousFunction()
  .then((ret) => {
    console.log(ret);
  });

console.log(ret);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69