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 27async function validateEmptyWrite() { 28 const filePathForHandle = path.resolve(tmpDir, 'tmp-empty-write.txt'); 29 const fileHandle = await open(filePathForHandle, 'w+'); 30 const buffer = Buffer.from(''); // empty buffer 31 32 await fileHandle.write(buffer, 0, buffer.length); 33 const readFileData = fs.readFileSync(filePathForHandle); 34 assert.deepStrictEqual(buffer, readFileData); 35} 36 37async function validateNonUint8ArrayWrite() { 38 const filePathForHandle = path.resolve(tmpDir, 'tmp-data-write.txt'); 39 const fileHandle = await open(filePathForHandle, 'w+'); 40 const buffer = Buffer.from('Hello world', 'utf8').toString('base64'); 41 42 await fileHandle.write(buffer, 0, buffer.length); 43 const readFileData = fs.readFileSync(filePathForHandle); 44 assert.deepStrictEqual(Buffer.from(buffer, 'utf8'), readFileData); 45} 46 47async function validateNonStringValuesWrite() { 48 const filePathForHandle = path.resolve(tmpDir, 'tmp-non-string-write.txt'); 49 const fileHandle = await open(filePathForHandle, 'w+'); 50 const nonStringValues = [123, {}, new Map()]; 51 for (const nonStringValue of nonStringValues) { 52 await fileHandle.write(nonStringValue); 53 } 54 55 const readFileData = fs.readFileSync(filePathForHandle); 56 const expected = ['123', '[object Object]', '[object Map]'].join(''); 57 assert.deepStrictEqual(Buffer.from(expected, 'utf8'), readFileData); 58} 59 60Promise.all([ 61 validateWrite(), 62 validateEmptyWrite(), 63 validateNonUint8ArrayWrite(), 64 validateNonStringValuesWrite() 65]).then(common.mustCall()); 66