Skip to content

Commit

Permalink
chore(utils): extend fs utils with createCacheReadStream and statCach… (
Browse files Browse the repository at this point in the history
  • Loading branch information
oxdev03 authored Aug 5, 2024
1 parent 1141b9d commit 5bdb821
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/util/fs/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
cachePathExists,
cachePathIsFile,
chmodLocalFile,
createCacheReadStream,
createCacheWriteStream,
deleteLocalFile,
ensureCacheDir,
Expand All @@ -32,6 +33,7 @@ import {
readSystemFile,
renameLocalFile,
rmCache,
statCacheFile,
statLocalFile,
writeLocalFile,
writeSystemFile,
Expand Down Expand Up @@ -332,6 +334,29 @@ describe('util/fs/index', () => {
});
});

describe('createCacheReadStream', () => {
it('creates read stream', async () => {
const path = `${cacheDir}/file.txt`;
const fileContent = 'foo';
await fs.outputFile(path, fileContent);

const stream = createCacheReadStream('file.txt');
expect(stream).toBeInstanceOf(fs.ReadStream);

let data = '';
stream.on('data', (chunk) => {
data += chunk.toString();
});

await new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});

expect(data).toBe(fileContent);
});
});

describe('localPathIsFile', () => {
it('returns true for file', async () => {
const path = `${localDir}/file.txt`;
Expand Down Expand Up @@ -431,6 +456,17 @@ describe('util/fs/index', () => {
});
});

describe('statCacheFile', () => {
it('returns stat object', async () => {
expect(await statCacheFile('foo')).toBeNull();

await fs.outputFile(`${cacheDir}/foo`, 'foobar');
const stat = await statCacheFile('foo');
expect(stat).toBeTruthy();
expect(stat!.isFile()).toBeTrue();
});
});

describe('listCacheDir', () => {
it('lists directory', async () => {
await fs.outputFile(`${cacheDir}/foo/bar.txt`, 'foobar');
Expand Down
16 changes: 16 additions & 0 deletions lib/util/fs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ export function createCacheWriteStream(path: string): fs.WriteStream {
return fs.createWriteStream(fullPath);
}

export function createCacheReadStream(path: string): fs.ReadStream {
const fullPath = ensureCachePath(path);
return fs.createReadStream(fullPath);
}

export async function localPathIsFile(pathName: string): Promise<boolean> {
const path = ensureLocalPath(pathName);
try {
Expand Down Expand Up @@ -249,6 +254,17 @@ export async function statLocalFile(
}
}

export async function statCacheFile(
pathName: string,
): Promise<fs.Stats | null> {
const path = ensureCachePath(pathName);
try {
return await fs.stat(path);
} catch (_) {
return null;
}
}

export function listCacheDir(
path: string,
options: { recursive: boolean } = { recursive: false },
Expand Down

0 comments on commit 5bdb821

Please sign in to comment.