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:
I added these two lines to the setting.js file:
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:
// 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.
Any ideas what i'm doing wrong?