Node.js - batchfile
Batch operations, transformations, and conversions on files.
Why?
Writing logic to
- iterate through files
- check that files exist
- read the file
- convert file
- check that destination directory exists
- if not, make the directory
- write the file
- be notified when all of the files are done
sucks.
Scenario
Let's assume that we have a collection of Markdown files with [Mustache][mustache] templates. We want to create HTML files from these Markdown files.
Let's assume that our Markdown looks like this:
My Biography============ By {{author}}------------- ... some text ...
Old-School Way
var marked = hogan = fs = path = mkdirp = ; var files = 'bio1.md' 'bio2.md' 'bio3.md';var authors = 'JP' 'Leslie' 'Chris';var pending = fileslength; files;
Yuck. Very long and hard to follow code. Yes, you can definitely simplify this by using libraries such as async, seq, or batchflow. batchtransform
itself uses batchflow.
Let's see the previous sample rewritten using batchfile
.
New-School way
var marked = hogan = btf = ; var files = 'bio1.md' 'bio2.md' 'bio3.md';var authors = 'JP' 'Leslie' 'Chris'; ;
Installation
npm install batchfile
Methods
batchfile(files)
Constructor function.
files: can be either an array or strings
Returns new BatchTransform object.
Example:
var batchfile = ;var myBatch = ;
transform(function(i, file, data, write){})
Transformation callback.
i: index of current iteration
file: file path
data: data buffer (don't forget to convert to a string)
write: the write callback. Call this last, and call it only once.
End callback is passed an array of written files.
read(function(i, file, data, done))
i: index of current iteration
file: file path
data: data buffer (don't forget to convert to a string)
done: the done callback. Call this last, and call it only once.
End callback is passed an array of what was passed to the parameter of the done function.
error(callback)
The error callback.
end(callback)
The end callback. The callback is passed different parameters depending upon which function was called above.
Author
node-batchfile
was written by JP Richardson. You should follow him on Twitter @jprichardson. Also read his coding blog Procbits. If you write software with others, you should checkout Gitpilot to make collaboration with Git simple.
License
(MIT License)
Copyright 2012, JP Richardson jprichardson@gmail.com