53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
import envPaths from 'env-paths'
|
|
import { sync as mkdir } from 'make-dir'
|
|
import { dirname } from 'path'
|
|
import { createWriteStream, createReadStream } from 'fs'
|
|
import crypto from 'crypto'
|
|
import debounce from 'debounce-fn'
|
|
|
|
function write (opts = {}) {
|
|
const path = opts.path ? opts.path : `${envPaths(opts.name || 'history', { suffix: null }).log}/${opts.name || process.pid}.log`
|
|
mkdir(dirname(path)) // makes recursively for any missing parent directories
|
|
|
|
const create = (path, clear) => {
|
|
const stream = createWriteStream(path, { flags: `${clear ? 'w' : 'a'}` })
|
|
// todo make sure stream was made
|
|
stream.on('close', (data) => {
|
|
console.log('the stream to history file was closed')
|
|
})
|
|
return stream
|
|
}
|
|
|
|
let output = create(path, opts.clear)
|
|
|
|
const _write = (obj) => {
|
|
if (output.writable) {
|
|
const tStamp = new Date()
|
|
const keys = {
|
|
_id: crypto.randomBytes(8).toString('hex'),
|
|
time: tStamp.getTime(),
|
|
datetime: tStamp.toString(),
|
|
utc: tStamp.toISOString()
|
|
}
|
|
if (typeof obj === 'string') obj = { msg: obj }
|
|
obj = Object.assign(keys, opts.keys, obj)
|
|
console.log('writing', obj)
|
|
output.write(JSON.stringify(obj) + '\n', function () {
|
|
debounce(output.destroy.bind(output), { wait: opts.close || 5000 })()
|
|
})
|
|
} else {
|
|
console.log('there is no stream, recreating')
|
|
output = create(path)
|
|
_write(obj)
|
|
}
|
|
}
|
|
return _write
|
|
}
|
|
|
|
function view (handler, opts) {
|
|
|
|
}
|
|
|
|
export default write
|
|
export { write, view }
|