File node: how to create an uniquely named file every time the node gets data passed through it?

My basic flow is getting an image URL, using the image-tools and file-in node to save that image to a file on my local server. I can then forward the new local URL, for home automation purposes.

I'm trying to get the file-in node to write every single request as a new file. Preferably logically, like file1.jpg, file2.jpg, etcetera. Currently I have it writing the file to /local/file.jpg, but I want to have every new image coming in to be written to an unique file.

What's the best way to achieve this?

put a change node before the file node to add a time stamp to the filename.

I prefer to have it be file1, file2, file3, etc. What's the best way to achieve that?

Additionally do you have an example on how to change the filename to a variable? Is it msg.filename? What would the code look like with the jpeg part at the end?

Then you'll need to keep track on counting.

var c = context.get('c') || 0
c ++

var path = "path/to/your/desired/folder/image_"+c+".jpg"
msg.filename = path
return msg;

And you'll need to use persistent context storage option, to keep counting survive the restart of Node-RED

And even then it is not the most reliable way to do it.


Thank you for this! I have an mqtt broker running that cpuld help with surviving node red restarts. Could that be used of persistent context storage? If not, how do I get it to stay persistent?

And if this isn't the most reliable way, how would you do it instead?

Most reliable will be to examine previously saved files , parse names to be sure they are consecutively saved and figure out name for new file. Also folder should be changed if certain amount of files already saved to one folder to preserve manteanability and keep performance of file system steady.

1 Like

If you use a Retained topic in MQTT then that will remember it for you. Alternatively you could use Persistent Context in node-red.

[Edit] But I like @hotNipi's idea better.

It is a good approach in my opinion. It could be easily implemented with the help of node " fs-ops-dir" from "node-red-contrib-fs-ops". This node will return in msg.files (you chose the name of the property) an array with the name of the files inside a given folder. You can then use a function node to get what is the index to be used for the next file name.

msg.payload = msg.files.length;
return msg;
1 Like

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