1// Flags: --experimental-abortcontroller 2'use strict'; 3 4const common = require('../common'); 5 6const assert = require('assert'); 7const path = require('path'); 8const { writeFile, readFile } = require('fs').promises; 9const tmpdir = require('../common/tmpdir'); 10tmpdir.refresh(); 11 12const fn = path.join(tmpdir.path, 'large-file'); 13 14// Creating large buffer with random content 15const largeBuffer = Buffer.from( 16 Array.apply(null, { length: 16834 * 2 }) 17 .map(Math.random) 18 .map((number) => (number * (1 << 8))) 19); 20 21async function createLargeFile() { 22 // Writing buffer to a file then try to read it 23 await writeFile(fn, largeBuffer); 24} 25 26async function validateReadFile() { 27 const readBuffer = await readFile(fn); 28 assert.strictEqual(readBuffer.equals(largeBuffer), true); 29} 30 31async function validateReadFileProc() { 32 // Test to make sure reading a file under the /proc directory works. Adapted 33 // from test-fs-read-file-sync-hostname.js. 34 // Refs: 35 // - https://groups.google.com/forum/#!topic/nodejs-dev/rxZ_RoH1Gn0 36 // - https://github.com/nodejs/node/issues/21331 37 38 // Test is Linux-specific. 39 if (!common.isLinux) 40 return; 41 42 const hostname = await readFile('/proc/sys/kernel/hostname'); 43 assert.ok(hostname.length > 0); 44} 45 46function validateReadFileAbortLogicBefore() { 47 const controller = new AbortController(); 48 const signal = controller.signal; 49 controller.abort(); 50 assert.rejects(readFile(fn, { signal }), { 51 name: 'AbortError' 52 }); 53} 54 55function validateReadFileAbortLogicDuring() { 56 const controller = new AbortController(); 57 const signal = controller.signal; 58 process.nextTick(() => controller.abort()); 59 assert.rejects(readFile(fn, { signal }), { 60 name: 'AbortError' 61 }); 62} 63 64async function validateWrongSignalParam() { 65 // Verify that if something different than Abortcontroller.signal 66 // is passed, ERR_INVALID_ARG_TYPE is thrown 67 68 await assert.rejects(async () => { 69 const callback = common.mustNotCall(() => {}); 70 await readFile(fn, { signal: 'hello' }, callback); 71 }, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' }); 72 73} 74 75(async () => { 76 await createLargeFile(); 77 await validateReadFile(); 78 await validateReadFileProc(); 79 await validateReadFileAbortLogicBefore(); 80 await validateReadFileAbortLogicDuring(); 81 await validateWrongSignalParam(); 82})().then(common.mustCall()); 83