I’m reading a line on NodeJS and insert it into an array however i need to export it to JavaScript file in order to use it there. however I’m having difficulty since the array arrives but outside the function it’s empty. so I’m wondering if anyone is able to fix this issue or help another way to send this array from NodeJS to JavaScript.
const test = [];
export function message(n){
for (var i = 0; i< n.length; i++){
test[i] = n[0];
}
//works
console.log(test[0]);
}
//outside of function
//doesn't work
console.log(test[0]);
I was hoping to access the array outside the function and be able to utilized all it’s features.
2
Answers
You are exporting a function that you have defined so you would need to import that function into another file and invoke it.
It’s not clear exactly what your use case is but imagine you are just experimenting with export/import so here is a really basic example of how to export/import a function along the lines of your use case:
message.js
This will take an interable and return the new array
test
.app.js
The
console.log
outside of themessage
function is being executed before your external invocation of themessage
function.However, I think you’re already doing what you want to do, just not quite. You can create a log function in the same scope as the
message
function, then invoke it from withinmessage
. E.g.,This way 👆🏻, you can access
test
from within the same scope asmessage
.