1'use strict'; 2 3const common = require('../common'); 4 5// The following tests validate base functionality for the fs.promises 6// FileHandle.write method. 7 8const fs = require('fs'); 9const { open } = fs.promises; 10const path = require('path'); 11const tmpdir = require('../common/tmpdir'); 12const assert = require('assert'); 13const tmpDir = tmpdir.path; 14 15tmpdir.refresh(); 16 17async function validateWrite() { 18 const filePathForHandle = path.resolve(tmpDir, 'tmp-write.txt'); 19 const fileHandle = await open(filePathForHandle, 'w+'); 20 const buffer = Buffer.from('Hello world'.repeat(100), 'utf8'); 21 22 await fileHandle.write(buffer, 0, buffer.length); 23 const readFileData = fs.readFileSync(filePathForHandle); 24 assert.deepStrictEqual(buffer, readFileData); 25 26 await fileHandle.close(); 27} 28 29async function validateEmptyWrite() { 30 const filePathForHandle = path.resolve(tmpDir, 'tmp-empty-write.txt'); 31 const fileHandle = await open(filePathForHandle, 'w+'); 32 const buffer = Buffer.from(''); // empty buffer 33 34 await fileHandle.write(buffer, 0, buffer.length); 35 const readFileData = fs.readFileSync(filePathForHandle); 36 assert.deepStrictEqual(buffer, readFileData); 37 38 await fileHandle.close(); 39} 40 41async function validateNonUint8ArrayWrite() { 42 const filePathForHandle = path.resolve(tmpDir, 'tmp-data-write.txt'); 43 const fileHandle = await open(filePathForHandle, 'w+'); 44 const buffer = Buffer.from('Hello world', 'utf8').toString('base64'); 45 46 await fileHandle.write(buffer, 0, buffer.length); 47 const readFileData = fs.readFileSync(filePathForHandle); 48 assert.deepStrictEqual(Buffer.from(buffer, 'utf8'), readFileData); 49 50 await fileHandle.close(); 51} 52 53async function validateNonStringValuesWrite() { 54 const filePathForHandle = path.resolve(tmpDir, 'tmp-non-string-write.txt'); 55 const fileHandle = await open(filePathForHandle, 'w+'); 56 const nonStringValues = [ 57 123, {}, new Map(), null, undefined, 0n, () => {}, Symbol(), true, 58 new String('notPrimitive'), 59 { toString() { return 'amObject'; } }, 60 { [Symbol.toPrimitive]: (hint) => 'amObject' }, 61 ]; 62 for (const nonStringValue of nonStringValues) { 63 await assert.rejects( 64 fileHandle.write(nonStringValue), 65 { message: /"buffer"/, code: 'ERR_INVALID_ARG_TYPE' } 66 ); 67 } 68 69 await fileHandle.close(); 70} 71 72Promise.all([ 73 validateWrite(), 74 validateEmptyWrite(), 75 validateNonUint8ArrayWrite(), 76 validateNonStringValuesWrite(), 77]).then(common.mustCall()); 78