diff --git a/lib/binding.js b/lib/binding.js index 00b04aa..bb1ed86 100644 --- a/lib/binding.js +++ b/lib/binding.js @@ -722,7 +722,7 @@ Binding.prototype.writeString = function ( callback(err, written, returned && string); }; } - return this.writeBuffer(fd, buffer, 0, string.length, position, wrapper, ctx); + return this.writeBuffer(fd, buffer, 0, buffer.length, position, wrapper, ctx); }; /** @@ -878,7 +878,7 @@ Binding.prototype.readFileUtf8 = function (name, flags) { */ Binding.prototype.writeFileUtf8 = function (filepath, data, flags, mode) { const destFd = this.open(filepath, flags, mode); - this.writeBuffer(destFd, data, 0, data.length); + this.writeString(destFd, data, null, 'utf8'); }; /** diff --git a/test/lib/encoding.spec.js b/test/lib/encoding.spec.js new file mode 100644 index 0000000..8a96936 --- /dev/null +++ b/test/lib/encoding.spec.js @@ -0,0 +1,39 @@ +const helper = require('../helper.js'); +const assert = helper.assert; +const fs = require('fs'); +const mock = require('../../lib/index.js'); + +const CHARS = [ + // // 1 utf-16, 1 utf-8 byte + 'A', + + // 1 utf-16 code unit, 3 utf-8 bytes + '’', + + // // 2 utf-16 code units, 4 utf-8 bytes + '😄', +]; + +const ENCODINGS = ['utf8', 'utf16le', 'latin1']; + +for (const encoding of ENCODINGS) { + for (const char of CHARS) { + describe(`Encoding (${encoding} ${char})`, () => { + const buffer = Buffer.from(char, encoding); + + beforeEach(() => mock()); + afterEach(() => mock.restore()); + + beforeEach(() => fs.writeFileSync('file', char, {encoding})); + + it(`writes ${buffer.length} bytes`, () => { + assert.strictEqual(fs.statSync('file').size, buffer.length); + }); + + it('reads the written value (buffer)', () => { + const out = fs.readFileSync('file'); + assert.sameOrderedMembers(Array.from(out), Array.from(buffer)); + }); + }); + } +}