Skip to content

Commit 3e53789

Browse files
authored
Merge pull request #12 from pmcelhaney/read-a-file
add a read() function
2 parents 091b25a + 26a21d8 commit 3e53789

File tree

4 files changed

+26
-1
lines changed

4 files changed

+26
-1
lines changed

.changeset/tall-spies-yell.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"using-temporary-files": minor
3+
---
4+
5+
added a read() function

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ await usingTemporaryFiles(async ({ path, add, addDirectory, remove }) => {
2121
path("."); // full path to the temporary directory
2222
path("file.txt"); // full path to a particular file
2323
await add("file.txt", "content"); // add a file
24+
const text = await read("file.txt" /*, encoding (optional) */); // read the contents of a file
2425
await addDirectory("dir"); // add a directory
2526
await remove("file.txt"); // remove a file
2627
});

src/using-temporary-files.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,14 @@ function createRemoveFunction(basePath) {
4141
};
4242
}
4343

44+
function createReadFunction(basePath) {
45+
return async function read(filePath, encoding = "utf8") {
46+
const fullPath = nodePath.join(basePath, filePath);
47+
48+
return fs.readFile(fullPath, encoding);
49+
};
50+
}
51+
4452
export async function usingTemporaryFiles(...callbacks) {
4553
const baseDirectory = DEBUG
4654
? nodePath.resolve(process.cwd(), "./")
@@ -56,7 +64,7 @@ export async function usingTemporaryFiles(...callbacks) {
5664
add: createAddFunction(temporaryDirectory),
5765
remove: createRemoveFunction(temporaryDirectory),
5866
addDirectory: createAddDirectoryFunction(temporaryDirectory),
59-
67+
read: createReadFunction(temporaryDirectory),
6068
path(...relativePaths) {
6169
return nodePath.join(temporaryDirectory, ...relativePaths);
6270
},

test/using-temporary-files.test.js

+11
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,17 @@ describe("usingTemporaryFiles", () => {
2727
expect(timesCallbackCalled).toBe(1);
2828
});
2929

30+
it("read a file", async () => {
31+
let timesCallbackCalled = 0;
32+
await usingTemporaryFiles(async ({ add, read }) => {
33+
timesCallbackCalled++;
34+
await add("file.txt", "Hello, world!");
35+
expect(await read("file.txt")).toBe("Hello, world!");
36+
});
37+
38+
expect(timesCallbackCalled).toBe(1);
39+
});
40+
3041
it("add a directory", async () => {
3142
let timesCallbackCalled = 0;
3243
await usingTemporaryFiles(async ({ path, addDirectory }) => {

0 commit comments

Comments
 (0)