Does the "function" node have a bug?

Hi Community,

I currently try to use Nodered to process PDF files. So I tried I'm testing a very simple flow like "reading a local PDF file" and then "extracting text" with a function.

The object returned by the PDF node is an array with the first level being the pages (in my case page 0 and page 1) and the second one containing the text elements with 4 features. In my use case, I try to retrieve the text ie "t" element.

Then using the function node, I noticed a strange behaviour in my function code.

When I use """let eli = pdf[i].t""" the node works fine and returns the payload. But when I use (and I need it for further computation) """let eli = pdf[i+1].t""" it returns a "TypeError"

I tried to declare "i" at the beginning of the code, but nothing changes.
Am I missing something?

Looks like an "off-by-one" error to me.

The last iteration won't work, because you access an index larger than the array's length. The last iteration of pdf[i+1] yields undefined, hence the type error.

1 Like

@kuema is right.

Here's a playground for you to practice the iteration

let pdf = [{ name: 'first', t: 0 }, { name: 'second', t: 1 }, { name: 'third', t: 2 }]
let len = pdf.length
node.warn(pdf)
node.warn(len)


for(let i = 0;i<=len-1;i++){
    node.warn('a) i: ' + i + ' | pdf[i+1]: ' + pdf[i+1])
}
// i<=len-1
// is same as
// i < len
// so you can remove that overcomplication

for (let i = 0; i < len; i++) {
    node.warn('b) i: ' + i + ' | pdf[i+1]: ' + pdf[i + 1])
}

// But your problem is that in case of i==2 the pdf[i+1] 
// tries to reach an element from outside
// of array boundaries. (pdf[3] desn't exist) The result is undefined
// You can't ask any property (pdf[3].t) of undefined

//this will now fail
for (let i = 0; i < len; i++) {
    node.warn('b) i: ' + i + ' | pdf[i+1].t: ' + pdf[i + 1].t)
}
6 Likes

Hi @kuema, @hotNipi,

You're right. Reading now your responses, it appears quite obvious. I confused length and boundary index. By limiting the loop to "i<=len-2" (or "i<len-1") it works. I got to be more watchful.

Anyway thanks a lot to you, I thought I was stuck here.
Cheers,
Jase

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.