1'use strict'; 2 3const common = require('../common'); 4const fixtures = require('../common/fixtures'); 5const assert = require('assert'); 6const path = require('path'); 7const fs = require('fs'); 8const os = require('os'); 9 10function pathToFileURL(p) { 11 if (!path.isAbsolute(p)) 12 throw new Error('Path must be absolute'); 13 if (common.isWindows && p.startsWith('\\\\')) 14 p = p.slice(2); 15 return new URL(`file://${p}`); 16} 17 18const p = path.resolve(fixtures.fixturesDir, 'a.js'); 19const url = pathToFileURL(p); 20 21assert(url instanceof URL); 22 23// Check that we can pass in a URL object successfully 24fs.readFile(url, common.mustSucceed((data) => { 25 assert(Buffer.isBuffer(data)); 26})); 27 28// Check that using a non file:// URL reports an error 29const httpUrl = new URL('http://example.org'); 30 31assert.throws( 32 () => { 33 fs.readFile(httpUrl, common.mustNotCall()); 34 }, 35 { 36 code: 'ERR_INVALID_URL_SCHEME', 37 name: 'TypeError', 38 message: 'The URL must be of scheme file' 39 }); 40 41// pct-encoded characters in the path will be decoded and checked 42if (common.isWindows) { 43 // Encoded back and forward slashes are not permitted on windows 44 ['%2f', '%2F', '%5c', '%5C'].forEach((i) => { 45 assert.throws( 46 () => { 47 fs.readFile(new URL(`file:///c:/tmp/${i}`), common.mustNotCall()); 48 }, 49 { 50 code: 'ERR_INVALID_FILE_URL_PATH', 51 name: 'TypeError', 52 message: 'File URL path must not include encoded \\ or / characters' 53 } 54 ); 55 }); 56 assert.throws( 57 () => { 58 fs.readFile(new URL('file:///c:/tmp/%00test'), common.mustNotCall()); 59 }, 60 { 61 code: 'ERR_INVALID_ARG_VALUE', 62 name: 'TypeError', 63 message: 'The argument \'path\' must be a string or Uint8Array without ' + 64 "null bytes. Received 'c:\\\\tmp\\\\\\x00test'" 65 } 66 ); 67} else { 68 // Encoded forward slashes are not permitted on other platforms 69 ['%2f', '%2F'].forEach((i) => { 70 assert.throws( 71 () => { 72 fs.readFile(new URL(`file:///c:/tmp/${i}`), common.mustNotCall()); 73 }, 74 { 75 code: 'ERR_INVALID_FILE_URL_PATH', 76 name: 'TypeError', 77 message: 'File URL path must not include encoded / characters' 78 }); 79 }); 80 assert.throws( 81 () => { 82 fs.readFile(new URL('file://hostname/a/b/c'), common.mustNotCall()); 83 }, 84 { 85 code: 'ERR_INVALID_FILE_URL_HOST', 86 name: 'TypeError', 87 message: `File URL host must be "localhost" or empty on ${os.platform()}` 88 } 89 ); 90 assert.throws( 91 () => { 92 fs.readFile(new URL('file:///tmp/%00test'), common.mustNotCall()); 93 }, 94 { 95 code: 'ERR_INVALID_ARG_VALUE', 96 name: 'TypeError', 97 message: "The argument 'path' must be a string or Uint8Array without " + 98 "null bytes. Received '/tmp/\\x00test'" 99 } 100 ); 101} 102