extract writeFileLines into its own function

pull/5/head
mehdi 3 years ago
parent 69604244d4
commit 8b984f1274
  1. 48
      lib/storage.js

@ -71,6 +71,34 @@ storage.flushToStorage = (options, callback) => {
}) })
} }
/**
* Fully write or rewrite the datafile
* @param {String} filename
* @param {String[]} lines
* @param {Function} callback
*/
storage.writeFileLines = (filename, lines, callback = () => {}) => {
try {
const stream = fs.createWriteStream(filename)
const readable = Readable.from(lines)
readable.on('data', (line) => {
try {
stream.write(line)
stream.write('\n')
} catch (err) {
callback(err)
}
})
readable.on('end', () => {
stream.close(callback)
})
readable.on('error', callback)
stream.on('error', callback)
} catch (err) {
callback(err)
}
}
/** /**
* Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost) * Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
* @param {String} filename * @param {String} filename
@ -89,25 +117,7 @@ storage.crashSafeWriteFileLines = (filename, lines, callback = () => {}) => {
}) })
}, },
cb => { cb => {
try { storage.writeFileLines(tempFilename, lines, cb)
const stream = fs.createWriteStream(tempFilename)
const readable = Readable.from(lines)
readable.on('data', (line) => {
try {
stream.write(line)
stream.write('\n')
} catch (err) {
cb(err)
}
})
readable.on('end', () => {
stream.close(cb)
})
readable.on('error', cb)
stream.on('error', cb)
} catch (err) {
cb(err)
}
}, },
async.apply(storage.flushToStorage, tempFilename), async.apply(storage.flushToStorage, tempFilename),
cb => { cb => {

Loading…
Cancel
Save