Node.js: conditional file streams
Writable file stream that can write to different files based upon the condition
of what's being written. i.e. Intead of passing filePath
as the first
parameter to your stream, you pass a function that returns the path.
This saves you time because you no longer have to manage many different writable streams.
Use Case
Best use case is to only have one writable fs stream that writes log files, except the log file path changes depending up the date or log data.
Usage
npm i --save cfs
Example 1
Write log data to different files depending upon the date.
var cfs = var path = var ymd = var { // get date in YYYY-MM-dd var date = return path} var logWriter = cfslogWriter
Example 2
Write data to different files depending upon what's being written.
Write even numbers to evens.txt
and odd numbers to odds.txt
.
No need to worry about opening a bunch of files. File descriptors are cached.
var cfs = var { if data == null return null if % 2 === 0 return 'evens.txt' else return 'odds.txt' } var logWriter = cfslogWriter
API
createWriteStream()
pathFunction
: A function that should return the path. Method signature(data, encoding)
.options
: These are the standard options that you'd pass tofs.createWriteStream
. Also,cacheOptions
which are the options that you'd pass tolru-cache
.
License
MIT
Copyright (c) JP Richardson