Skip to content

Commit 0a12ed2

Browse files
committed
fix: ensure dirname(file) exists
1 parent abe4399 commit 0a12ed2

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

src/index.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { promises as fs } from 'fs'
2-
import { resolve } from 'path'
2+
import { resolve, dirname } from 'path'
33

44
const _memo = {
55
_pid: process.pid
@@ -12,11 +12,11 @@ interface MemoOptions {
1212
}
1313

1414
export async function getMemo (config: Partial<MemoOptions>): Promise<any> {
15-
const options = getOptions(config)
15+
const file = getFile(config)
1616

1717
// Try to load latest memo
1818
try {
19-
const memo = JSON.parse(await fs.readFile(options.file, 'utf-8')) || {}
19+
const memo = JSON.parse(await fs.readFile(file, 'utf-8')) || {}
2020
if (!memo._pid) {
2121
throw new Error('Memo lacks _pid')
2222
}
@@ -35,23 +35,25 @@ export async function getMemo (config: Partial<MemoOptions>): Promise<any> {
3535
}
3636

3737
export async function setMemo (memo: object, config: Partial<MemoOptions>): Promise<void> {
38-
const options = getOptions(config)
38+
const file = getFile(config)
3939

4040
// Set local memo
4141
Object.assign(_memo, memo)
4242
_memo._pid = process.pid
4343

4444
// Try to persist
45-
try { await fs.mkdir(options.dir) } catch (e) { }
46-
try { await fs.writeFile(options.file, JSON.stringify(_memo), 'utf-8') } catch (e) { }
45+
try { await fs.mkdir(dirname(file)) } catch (e) { }
46+
try { await fs.writeFile(file, JSON.stringify(_memo), 'utf-8') } catch (e) { }
4747
}
4848

49-
function getOptions (config: Partial<MemoOptions>): MemoOptions {
50-
const options = { ...config }
51-
options.name = options.name || 'default'
52-
options.dir = options.dir || resolve(process.cwd(), 'node_modules/.cache/fs-memo')
53-
options.file = options.file || resolve(options.dir, options.name + '.json')
54-
return options as MemoOptions
49+
function getFile (config: Partial<MemoOptions>): string {
50+
if (config.file) {
51+
return config.file
52+
}
53+
return resolve(
54+
config.dir || resolve(process.cwd(), 'node_modules/.cache/fs-memo'),
55+
(config.name || 'default') + '.json'
56+
)
5557
}
5658

5759
function isAlive (pid: number): Boolean {

0 commit comments

Comments
 (0)