diff --git a/.changeset/tall-spies-yell.md b/.changeset/tall-spies-yell.md new file mode 100644 index 0000000..cb1fe34 --- /dev/null +++ b/.changeset/tall-spies-yell.md @@ -0,0 +1,5 @@ +--- +"using-temporary-files": minor +--- + +added a read() function diff --git a/README.md b/README.md index bf684e3..243424d 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ await usingTemporaryFiles(async ({ path, add, addDirectory, remove }) => { path("."); // full path to the temporary directory path("file.txt"); // full path to a particular file await add("file.txt", "content"); // add a file + const text = await read("file.txt" /*, encoding (optional) */); // read the contents of a file await addDirectory("dir"); // add a directory await remove("file.txt"); // remove a file }); diff --git a/src/using-temporary-files.js b/src/using-temporary-files.js index ddcb402..1f6fc60 100644 --- a/src/using-temporary-files.js +++ b/src/using-temporary-files.js @@ -41,6 +41,14 @@ function createRemoveFunction(basePath) { }; } +function createReadFunction(basePath) { + return async function read(filePath, encoding = "utf8") { + const fullPath = nodePath.join(basePath, filePath); + + return fs.readFile(fullPath, encoding); + }; +} + export async function usingTemporaryFiles(...callbacks) { const baseDirectory = DEBUG ? nodePath.resolve(process.cwd(), "./") @@ -56,7 +64,7 @@ export async function usingTemporaryFiles(...callbacks) { add: createAddFunction(temporaryDirectory), remove: createRemoveFunction(temporaryDirectory), addDirectory: createAddDirectoryFunction(temporaryDirectory), - + read: createReadFunction(temporaryDirectory), path(...relativePaths) { return nodePath.join(temporaryDirectory, ...relativePaths); }, diff --git a/test/using-temporary-files.test.js b/test/using-temporary-files.test.js index 0e5d5b4..9428a05 100644 --- a/test/using-temporary-files.test.js +++ b/test/using-temporary-files.test.js @@ -27,6 +27,17 @@ describe("usingTemporaryFiles", () => { expect(timesCallbackCalled).toBe(1); }); + it("read a file", async () => { + let timesCallbackCalled = 0; + await usingTemporaryFiles(async ({ add, read }) => { + timesCallbackCalled++; + await add("file.txt", "Hello, world!"); + expect(await read("file.txt")).toBe("Hello, world!"); + }); + + expect(timesCallbackCalled).toBe(1); + }); + it("add a directory", async () => { let timesCallbackCalled = 0; await usingTemporaryFiles(async ({ path, addDirectory }) => {