mirror of https://github.com/seald/nedb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.8 KiB
60 lines
1.8 KiB
4 years ago
|
/* eslint-env mocha */
|
||
9 years ago
|
/**
|
||
|
* Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
|
||
|
*/
|
||
4 years ago
|
const fs = require('fs')
|
||
3 years ago
|
const { Writable } = require('stream')
|
||
|
const { callbackify } = require('util')
|
||
|
|
||
|
fs.promises.writeFile = async function (path, data) {
|
||
|
let onePassDone = false
|
||
|
const options = { encoding: 'utf8', mode: 0o666, flag: 'w' } // we don't care about the actual options passed
|
||
|
|
||
|
const filehandle = await fs.promises.open(path, options.flag, options.mode)
|
||
|
const buffer = (data instanceof Buffer) ? data : Buffer.from('' + data, options.encoding || 'utf8')
|
||
|
let length = buffer.length
|
||
|
let offset = 0
|
||
|
|
||
|
try {
|
||
|
while (length > 0) {
|
||
|
if (onePassDone) { process.exit(1) } // Crash on purpose before rewrite done
|
||
|
const { bytesWritten } = await filehandle.write(buffer, offset, Math.min(5000, length)) // Force write by chunks of 5000 bytes to ensure data will be incomplete on crash
|
||
|
onePassDone = true
|
||
|
offset += bytesWritten
|
||
|
length -= bytesWritten
|
||
9 years ago
|
}
|
||
3 years ago
|
} finally {
|
||
|
await filehandle.close()
|
||
4 years ago
|
}
|
||
9 years ago
|
}
|
||
|
|
||
3 years ago
|
class FakeFsWriteStream extends Writable {
|
||
|
constructor (filename) {
|
||
|
super()
|
||
|
this.filename = filename
|
||
|
this._content = Buffer.alloc(0)
|
||
9 years ago
|
}
|
||
|
|
||
3 years ago
|
_write (chunk, encoding, callback) {
|
||
|
this._content = Buffer.concat([this._content, Buffer.from(chunk, encoding)])
|
||
|
callback()
|
||
9 years ago
|
}
|
||
|
|
||
3 years ago
|
_end (chunk, encoding, callback) {
|
||
|
this._content = Buffer.concat([this._content, Buffer.from(chunk, encoding)])
|
||
|
callback()
|
||
9 years ago
|
}
|
||
|
|
||
3 years ago
|
close (callback) {
|
||
|
callbackify(fs.promises.writeFile)(this.filename, this._content, 'utf8', callback)
|
||
9 years ago
|
}
|
||
4 years ago
|
}
|
||
9 years ago
|
|
||
3 years ago
|
fs.createWriteStream = path => new FakeFsWriteStream(path)
|
||
3 years ago
|
|
||
3 years ago
|
// End of fs monkey patching
|
||
10 months ago
|
const Nedb = require('../cjs/datastore.cjs')
|
||
4 years ago
|
const db = new Nedb({ filename: 'workspace/lac.db' })
|
||
11 years ago
|
|
||
3 years ago
|
db.loadDatabaseAsync() // no need to await
|