Basic text manipulation - how?

Greetings,

New n8n explorer here. Just dowloaded the Mac app and am tinkering using my local file system. I was able to copy a text file from one folder to another, but now I want to do a simple search and replace before saving.

Are there nodes for doing basic string manipulation, or must that be done with (eeeww) code? I don’t see anything like a simple find and replace node. Am I looking in the wrong place, or am I stuck with using JS?

-Steve

I just want to copy a file and replace some text, and here’s my wf…

// Code here will run only once, no matter how many input items there are.
// More info and help: https://docs.n8n.io/nodes/n8n-nodes-base.function

for (item of items) {

  const b64FileContents = item.binary.file.data;
  let txtFileContents = Buffer.from( b64FileContents, 'base64' ).toString( 'ascii' );
  txtFileContents = txtFileContents.replace( 'someText', 'otherText' );
  
  item.binary.file.data = Buffer.from( txtFileContents ).toString( 'base64' );
}

// You can write logs to the browser console
console.log('Done!');

return items;

This works, but is it the best approach? There appears to be no way to read a file as text - only binary. Any tips appreciated.

-Steve

Hi @shot, welcome to the community :tada:

You could rid yourself of at least a bit of code by using the Move Binary Data node after your Read Binary File node. In this example it moves the binary file content into the text JSON property:

For the replace operation you’d still need to use a bit of code at this stage, but it would only be a single expression when using the Set node for example.

You can then move the result back using another Move Binary Data node before writing it using the Write Binary File node.

Example Workflow

The above example workflow uses a Windows path, but I hope it still helps :wink:

1 Like

Super helpful! Thanks for taking the time!

I’ll need to study this and read up on expressions to really wrap my head around it. Might be back with questions.

3 Likes