I want to copy some files using Node.js. Basically, this is quite easy, but I have two special requirements I need to fulfill:
So, while this is not a complex task basically, I guess there are various ways how you could solve this. E.g., it would be nice if I could use a template engine to do the replacements, but on the other hand then I need to have the complete file as a string. I'd prefer a stream-based approach, but then - how should I do the replacing?
You see, lots of questions, and I am not able to decide which way to go.
Any hints, ideas, best practices, ...?
Or - is there a module yet that does this task?
You can write your own solution without reading the entire file. fs.readFile()
should only be used when you are 100% sure that the files are no longer than a buffer chunk (typically 8KB or 16KB).
The simplest solution is to create a readable stream, attach a data
event listener and iterate the buffer reading character by character. If you have a placeholder like this: ${label}
, then check if you find ${
, then set a flag to true. Begin storing the label name. If you find }
and flag is true then you've finished. Set flag to false and the temporal label string to ""
.
You don't need any template engine or extra module.