diff --git a/__test__/read_file.spec.ts b/__test__/read_file.spec.ts index 3a1fc66..d1224f1 100644 --- a/__test__/read_file.spec.ts +++ b/__test__/read_file.spec.ts @@ -36,6 +36,21 @@ test('readFile: async should throw on non-existent file', async (t) => { await t.throwsAsync(async () => await readFile('./no-such-file'), { message: /ENOENT/ }) }) +test('readFile: async should return string with encoding as string param', async (t) => { + const result = await readFile('./package.json', 'utf-8') + t.is(typeof result, 'string') +}) + +test('readFile: async should return string with encoding as options object', async (t) => { + const result = await readFile('./package.json', { encoding: 'utf-8' }) + t.is(typeof result, 'string') +}) + +test('readFile: async should return Buffer with no encoding', async (t) => { + const result = await readFile('./package.json') + t.true(Buffer.isBuffer(result)) +}) + test('dual-run: readFileSync Buffer should match node:fs byte-for-byte', (t) => { const nodeResult = nodeFs.readFileSync('./package.json') const hyperResult = readFileSync('./package.json') as Buffer diff --git a/src/read_file.rs b/src/read_file.rs index 6837a3a..837bb75 100644 --- a/src/read_file.rs +++ b/src/read_file.rs @@ -66,15 +66,28 @@ pub struct ReadFileOptions { pub flag: Option, } +fn normalize_read_file_options( + options: Option>, +) -> ReadFileOptions { + match options { + Some(Either::A(encoding)) => ReadFileOptions { + encoding: Some(encoding), + flag: None, + }, + Some(Either::B(opts)) => opts, + None => ReadFileOptions { + encoding: None, + flag: None, + }, + } +} + fn read_file_impl( path_str: String, - options: Option, + options: Option>, ) -> Result> { let path = Path::new(&path_str); - let opts = options.unwrap_or(ReadFileOptions { - encoding: None, - flag: None, - }); + let opts = normalize_read_file_options(options); let flag = opts.flag.as_deref().unwrap_or("r"); @@ -142,7 +155,7 @@ fn read_file_impl( #[napi(js_name = "readFileSync")] pub fn read_file_sync( path: String, - options: Option, + options: Option>, ) -> Result> { read_file_impl(path, options) } @@ -151,7 +164,7 @@ pub fn read_file_sync( pub struct ReadFileTask { pub path: String, - pub options: Option, + pub options: Option>, } impl Task for ReadFileTask { @@ -168,6 +181,9 @@ impl Task for ReadFileTask { } #[napi(js_name = "readFile")] -pub fn read_file(path: String, options: Option) -> AsyncTask { +pub fn read_file( + path: String, + options: Option>, +) -> AsyncTask { AsyncTask::new(ReadFileTask { path, options }) }