From 8b984f127477b76c27b8901ac7a36448a2e70173 Mon Sep 17 00:00:00 2001 From: mehdi Date: Fri, 15 Oct 2021 14:06:42 +0200 Subject: [PATCH] extract writeFileLines into its own function --- lib/storage.js | 48 +++++++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/lib/storage.js b/lib/storage.js index 612c759..4b0bfd7 100755 --- a/lib/storage.js +++ b/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) * @param {String} filename @@ -89,25 +117,7 @@ storage.crashSafeWriteFileLines = (filename, lines, callback = () => {}) => { }) }, cb => { - try { - 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) - } + storage.writeFileLines(tempFilename, lines, cb) }, async.apply(storage.flushToStorage, tempFilename), cb => {