I'm using p5.js for my project, and I have to load some data from a file in another folder.
My js code is written in 'js' folder, and the data file is in 'txt' folder. Both 'js' and 'txt' folders are in the same root directory.
Here's my code,
var data;
function preload() {
data = loadStrings('../txt/data.txt');
console.log(data);
console.log(data[0]);
}
and here's the logs:
0: "abcde"
1: "fghij"
2: "klmno"
length: 3
[[Prototype]]: Array(0)
undefined
and here's the request:
Request URL: http://localhost:3000/txt/data.txt
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin
It shows appropriate result when I print whole array, but when I access each data of array, it goes something wrong. What's wrong in my project?
Since you are calling in the preload, you need to access the data in the setup or draw function.
function setup() {
console.log(data[0])
}
Otherwise, you will need to use a callback function to handle the data.
function setup() {
loadStrings('../txt/data.txt', myCallback);
}
function myCallback(data) {
console.log(data[0])
}