# Check If file exists - functionGlobalContext

**URL:** <https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507>\
**Category:** General\
**Tags:** function-node\
**Created:** [29 March 2022 18:51 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507 "2022-03-29T18:51:50Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![mk500](https://avatars.discourse-cdn.com/v4/letter/m/ac8455/32.png) [@mk500](https://discourse.nodered.org/u/mk500)\
**Post date:** [29 March 2022 18:51 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/1 "2022-03-29T18:51:50Z")

</div>

Hey,  
it's my first post here at the forum.

I simply want to check, if a file in my rasperry directory exist.

So I tried a few things. But don't get the right way. So I found this example. I like functions, so this one seems to be the best on for me. But I don't get working:

[Example](https://flows.nodered.org/flow/cdf160c36f082dc2a20cd1183ac6cd7d)

I added these two lines to the setting.js file:

```auto
functionGlobalContext: {

        // os:require('os'),

        // -- Pass in Libraries for convenience in function nodes -- //

        path : require('path'),

        fs : require('fs'),

    },

```

And put the code from the example in a function node:

```auto
// Sends a msg with full file path for each file in a given folder ending with given extension
// PARAMETERS:
// msg.payload.folder {string} Folder to look in for files
// msg.payload.ext {string} The file extension to look for
// ASSUMPTIONS:
// Node.JS libraries fs and path have been required in the functionGlobal section of settings.js
// Tested using Node.JS v4.4.5 LTS and Node-Red 0.13.4
// NOTES:
// You would almost certainly be better off using one of the "glob" modules such as glob-fs, node-glob or glob-all

var fs = global.get('fs1')
var path = global.get('path')

// Give up if fs or path have not been assigned to global context (see assumption 1)
if ( (typeof fs !== 'undefined') || (typeof path !== 'undefined') ) {
    node.error('Either fs or path modules could not be found in global context')
    return    
}
// And make sure they are functions
if ( (typeof fs !== 'object') || (typeof path !== 'object') ) {
    node.error('Either fs or path from global context is not an object & it must be')
    return    
}

var folder = msg.payload.folder || '/home/pi'
var extension = msg.payload.ext || '.gpx'

// Make sure the parameters are strings
if ( (typeof folder !== 'string') || (typeof extension !== 'string') ) {
    node.error('Either Folder or Ext is not a string, cannot process. Folder: ' + folder + ', Ext: ' + extension, err)
    return    
}

fs.readdir(folder, callback)

// readir is ASYNC so don't return msg here as
// it would be pointless

function callback(err, files) {
    if (err) {
        node.error('Oops! Folder does not exist: ' + folder, err)
        return
    }
    
    // Any error in here will crash Node-Red!! So catch them instead
    try {
        files
            .filter( filterOnExtension ) // calls the given callback func for each file, will only pass names where fn returns true
            .forEach( sendName )
    } catch (err) {
        node.error('Ouch! Something went badly wrong processing the files list', err)
        return
    }
}

function filterOnExtension(file) {
    var len = extension.length

    // Returns TRUE only if the file name ends in the given extension
    return file.substr(0-len) === extension
}

function sendName(file) {
        msg.payload = path.join(folder, file)
        node.send( msg )
}

```

But when I inject I got this error.

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/a/5/a5cfec685965e768bbf03f4d4fa603fd61b3299f.png)

Any ideas what i'm doing wrong?

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [29 March 2022 20:07 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/2 "2022-03-29T20:07:33Z")

</div>

Hi, welcome to the forum.

Common error. You've mixed up your "nots". `(typeof fs !== 'undefined') || (typeof path !== 'undefined')` is always going to be true. This should do it I think: `if ( !fs || !path )` 🙂

We've all done it.

---

<div class="post-metadata">

**Author:** ![mk500](https://avatars.discourse-cdn.com/v4/letter/m/ac8455/32.png) [@mk500](https://discourse.nodered.org/u/mk500)\
**Post date:** [30 March 2022 18:12 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/3 "2022-03-30T18:12:55Z")

</div>

ok that was simple 😃 Thanks for the quick response.  
I think I just focused to hard to the setting file.

But the code in the function is originally from your example, maybe you can change it, that will help other 🙂

> [@mk500](#):
>
> Example

But now I have another problem. In the folder where I check the files, will be only one .jpg-file.  
If it is there, I got the payload with path of directory.

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/d/d/ddc9fab288a78c0c2e27918f5a64f734cc430380.png)

But if its not there I don't get the error message of the callback function.  
But I need a "yes" or "no" to carry on.

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/6/3/63030e5da40c8e4ea6dadaa1167500d156a9263e.png)

Maybe you have an idea?

---

<div class="post-metadata">

**Author:** ![Paul-Reed](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/paul-reed/32/66906_2.png) [@Paul-Reed](https://discourse.nodered.org/u/Paul-Reed)\
**Post date:** [30 March 2022 18:33 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/4 "2022-03-30T18:33:51Z")

</div>

> [@mk500](#):
>
> But the code in the function is originally from your example

Please provide a link to that example, so that we can check it.

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [31 March 2022 18:21 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/5 "2022-03-31T18:21:51Z")

</div>

> [@mk500](#):
>
> But the code in the function is originally from your example, maybe you can change it, that will help other

Ah well - the falacy of assuming I know what I'm talking about! To be fair though. That was create **SIX YEARS AGO**! 😲 I'd forgotten all about it.

> [@Paul-Reed](#):
>
> Please provide a link to that example, so that we can check it.

Link is in the first post Paul and I can see that the OP is correct. In truth, I'd almost certainly do it a different way now in any case.

> [@mk500](#):
>
> But if its not there I don't get the error message of the callback function.  
> But I need a "yes" or "no" to carry on.

In the original post, you will see a reference to using a glob module and in fact, that's almost certainly what I'd do now. Using `fast-glob` you can pass a request such as `/home/pi/Desktop/*.jpg`, what you get back would be an array of paths. If there were no jpg files, you would get an empty array which, of course, you could test for.

Also, these days, you can have a package connected directly to a function node so you don't need to change settings.js nor abuse the globals.

---

<div class="post-metadata">

**Author:** ![mk500](https://avatars.discourse-cdn.com/v4/letter/m/ac8455/32.png) [@mk500](https://discourse.nodered.org/u/mk500)\
**Post date:** [31 March 2022 18:47 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/6 "2022-03-31T18:47:47Z")

</div>

> [@TotallyInformation](#):
>
> Using `fast-glob` you can pass a request such as `/home/pi/Desktop/*.jpg` , what you get back would be an array of paths. If there were no jpg files, you would get an empty array which, of course, you could test for.

I checked the github site of the 'fast-glob npm', but I didn't really get any smarter than that. Do you have an example how to use that? Or how the syntax is buildt? I think thats to deep in node.js for me.

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [31 March 2022 18:59 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/7 "2022-03-31T18:59:55Z")

</div>

This may help:

> [@Select files within a date range and merge them into one file](https://discourse.nodered.org/t/select-files-within-a-date-range-and-merge-them-into-one-file/59701/8):
>
> Here is another way to do it grinning Using just a function node. [image] You can use fs instead of fs-extra if you like but then you will end up with a more complex first line of the for block. fx-extra is used by Node-RED by the way. I'm using fast-glob here instead of using the fs-ops node. // Use Fast-Glob to get the list of files const entries = await fg(['\*/csv/\*.csv']) msg.entries = entries // get the files msg.files = [] let fline for (const fname of entries) { let f = await f…

---

<div class="post-metadata">

**Author:** ![mk500](https://avatars.discourse-cdn.com/v4/letter/m/ac8455/32.png) [@mk500](https://discourse.nodered.org/u/mk500)\
**Post date:** [3 April 2022 15:58 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/8 "2022-04-03T15:58:57Z")

</div>

Hey Julian,  
the example gave me some inspiration and yeah how easy and confortable it is to import the modules directly in the function node. 😉

Now I have a solution that works for me 🙂

```auto
fs.stat('/home/pi/Test/grab.jpg', function(err) {  
    if (err) {
       msg.payload = 0 // Datei existiert nicht
    } else {
        msg.payload = 1 // Datei existiert bereits
    }
});

return msg;

```

I need the function to grab a jpg file out of rtsp security cam stream and send via telegram.

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/f/3/f36f34c5ed5a53dbee21341201ba85d69cbb096b.png)

thanks for your help 💪🏻

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [17 April 2022 15:59 UTC](https://discourse.nodered.org/t/check-if-file-exists-functionglobalcontext/60507/9 "2022-04-17T15:59:41Z")

</div>

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