summaryrefslogtreecommitdiff
path: root/fs
diff options
context:
space:
mode:
authorVincent LE GOFF <g_n_s@hotmail.fr>2019-04-13 21:26:09 +0200
committerRyan Dahl <ry@tinyclouds.org>2019-04-13 15:26:09 -0400
commit99cedf40e7ce4ef0f1d53e759f3abee03347e313 (patch)
tree1613ee25ca34bf3993c7be2886845bd0b513d06e /fs
parent0c877a1283e1b36e6de61b7e345afae5e7f4981c (diff)
Added read file str (denoland/deno_std#276)
Original: https://github.com/denoland/deno_std/commit/b462ad253042c13c95d9b9b205920a17a12dae28
Diffstat (limited to 'fs')
-rw-r--r--fs/read_file_str.ts33
-rw-r--r--fs/read_file_str_test.ts20
-rw-r--r--fs/test.ts1
3 files changed, 54 insertions, 0 deletions
diff --git a/fs/read_file_str.ts b/fs/read_file_str.ts
new file mode 100644
index 000000000..9f87c9338
--- /dev/null
+++ b/fs/read_file_str.ts
@@ -0,0 +1,33 @@
+// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
+
+export interface ReadOptions {
+ encoding?: string;
+}
+
+/**
+ * Read file synchronously and output it as a string.
+ *
+ * @param filename File to read
+ * @param opts Read options
+ */
+export function readFileStrSync(
+ filename: string,
+ opts: ReadOptions = {}
+): string {
+ const decoder = new TextDecoder(opts.encoding);
+ return decoder.decode(Deno.readFileSync(filename));
+}
+
+/**
+ * Read file and output it as a string.
+ *
+ * @param filename File to read
+ * @param opts Read options
+ */
+export async function readFileStr(
+ filename: string,
+ opts: ReadOptions = {}
+): Promise<string> {
+ const decoder = new TextDecoder(opts.encoding);
+ return decoder.decode(await Deno.readFile(filename));
+}
diff --git a/fs/read_file_str_test.ts b/fs/read_file_str_test.ts
new file mode 100644
index 000000000..eb529022c
--- /dev/null
+++ b/fs/read_file_str_test.ts
@@ -0,0 +1,20 @@
+import { test } from "../testing/mod.ts";
+import { assert } from "../testing/asserts.ts";
+import { readFileStrSync, readFileStr } from "./read_file_str.ts";
+import * as path from "./path/mod.ts";
+
+const testdataDir = path.resolve("fs", "testdata");
+
+test(function testReadFileSync() {
+ const jsonFile = path.join(testdataDir, "json_valid_obj.json");
+ const strFile = readFileStrSync(jsonFile);
+ assert(typeof strFile === "string");
+ assert(strFile.length > 0);
+});
+
+test(async function testReadFile() {
+ const jsonFile = path.join(testdataDir, "json_valid_obj.json");
+ const strFile = await readFileStr(jsonFile);
+ assert(typeof strFile === "string");
+ assert(strFile.length > 0);
+});
diff --git a/fs/test.ts b/fs/test.ts
index cc9013eed..025c0efb2 100644
--- a/fs/test.ts
+++ b/fs/test.ts
@@ -10,5 +10,6 @@ import "./ensure_dir_test.ts";
import "./ensure_file_test.ts";
import "./move_test.ts";
import "./read_json_test.ts";
+import "./read_file_str_test.ts";
import "./write_json_test.ts";
import "./utils_test.ts";