Copy and convert the file using Node.js

I want to copy some files using Node.js. Basically it's pretty simple, but I have two specific requirements that I need to fulfill:

  • I need to parse the content of a file and replace some placeholders with actual values.
  • The filename can also contain a placeholder and I need to replace it with the actual value as well.

So, while this is not a difficult task in general, I am guessing that there are various ways to solve this problem. For example, it would be nice if I could use the template engine to replace, but on the other hand I need to have the complete file as a string. I would prefer to use a streaming approach, but then - how do I do the replacement?

You see, there are many questions and I cannot decide where to go.

Any tips, ideas, best practices, ...?

Or - is there still a module that does this task?

+3


source to share


1 answer


You can write your own solution without reading the whole file. fs.readFile()

should only be used when you are 100% sure that the files are no larger than a chunk of the buffer (usually 8KB or 16KB).

The simplest solution is to create a readable stream, attach an event listener, data

and iterate over the read buffer character by character. If you have a placeholder like this: ${label}

check if you find ${

and then set the flag to true. Start storing the label name. If you find }

and the flag is true, you're done. Set the flag to false and the timestamp string to ""

.



You don't need a templating engine or additional module.

+1


source







All Articles