|
|
|
@ -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 => { |
|
|
|
|