streaming write with `Readable.from`

pull/5/head
mehdi 3 years ago
parent 7404ee1bc2
commit 8c4f56a04a
  1. 20
      lib/storage.js

@ -10,6 +10,7 @@ const fs = require('fs')
const path = require('path') const path = require('path')
const async = require('async') const async = require('async')
const storage = {} const storage = {}
const { Readable } = require('stream')
// eslint-disable-next-line node/no-callback-literal // eslint-disable-next-line node/no-callback-literal
storage.exists = (path, cb) => fs.access(path, fs.constants.F_OK, (err) => { cb(!err) }) storage.exists = (path, cb) => fs.access(path, fs.constants.F_OK, (err) => { cb(!err) })
@ -90,17 +91,20 @@ storage.crashSafeWriteFileLines = (filename, lines, callback = () => {}) => {
cb => { cb => {
try { try {
const stream = fs.createWriteStream(tempFilename) const stream = fs.createWriteStream(tempFilename)
const next = () => { const readable = Readable.from(lines)
const line = lines.shift() readable.on('data', (line) => {
if (line === undefined) { try {
stream.close(cb)
} else {
stream.write(line) stream.write(line)
stream.write('\n') stream.write('\n')
setImmediate(next) } catch (err) {
cb(err)
} }
} })
next() readable.on('end', () => {
stream.close(cb)
})
readable.on('error', () => cb)
stream.on('error', () => cb)
} catch (err) { } catch (err) {
cb(err) cb(err)
} }

Loading…
Cancel
Save