mirror of
https://github.com/denoland/deno.git
synced 2024-12-28 10:09:20 -05:00
Added read file str (#276)
This commit is contained in:
parent
bb92c44c64
commit
b462ad2530
3 changed files with 54 additions and 0 deletions
33
fs/read_file_str.ts
Normal file
33
fs/read_file_str.ts
Normal file
|
@ -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));
|
||||||
|
}
|
20
fs/read_file_str_test.ts
Normal file
20
fs/read_file_str_test.ts
Normal file
|
@ -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);
|
||||||
|
});
|
|
@ -10,5 +10,6 @@ import "./ensure_dir_test.ts";
|
||||||
import "./ensure_file_test.ts";
|
import "./ensure_file_test.ts";
|
||||||
import "./move_test.ts";
|
import "./move_test.ts";
|
||||||
import "./read_json_test.ts";
|
import "./read_json_test.ts";
|
||||||
|
import "./read_file_str_test.ts";
|
||||||
import "./write_json_test.ts";
|
import "./write_json_test.ts";
|
||||||
import "./utils_test.ts";
|
import "./utils_test.ts";
|
||||||
|
|
Loading…
Reference in a new issue