Skip to content

Commit

Permalink
refactor: createFile() will return created file path
Browse files Browse the repository at this point in the history
  • Loading branch information
waitingsong committed Dec 27, 2018
1 parent 5201b6a commit 6ac4970
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
26 changes: 15 additions & 11 deletions src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,33 +102,37 @@ export async function createDir(path: string): Promise<void> {
* Create file
* Buffer will be written as binary
* Object will be written as JSON string
*
* @requires string - created file path
*/
export async function createFile(file: string, data: any, options?: WriteFileOptions): Promise<void> {
const path = dirname(file)
export async function createFile(file: string, data: any, options?: WriteFileOptions): Promise<string> {
const dir = dirname(file)

/* istanbul ignore next */
if (! path) {
throw new Error('path empty')
if (! dir) {
throw new Error('folder empty')
}
if (! await isDirExists(path)) {
await createDir(path)
if (! await isDirExists(dir)) {
await createDir(dir)
}
file = normalize(file)
const path = normalize(file)

/* istanbul ignore else */
if (!await isFileExists(file)) {
if (!await isFileExists(path)) {
const opts: WriteFileOptions = options ? options : { mode: 0o640 }

if (Buffer.isBuffer(data)) {
await writeFileAsync(file, data, opts)
await writeFileAsync(path, data, opts)
}
else if (typeof data === 'object') {
await writeFileAsync(file, JSON.stringify(data))
await writeFileAsync(path, JSON.stringify(data))
}
else {
await writeFileAsync(file, data, opts)
await writeFileAsync(path, data, opts)
}
}

return path
}


Expand Down
10 changes: 7 additions & 3 deletions test/10_shared_utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isFileExists,
isPathAcessible,
join,
normalize,
readFileAsync,
tmpdir,
} from '../src/shared/index'
Expand Down Expand Up @@ -119,7 +120,8 @@ describe(filename, () => {
const file = `${randomPath}/test`

try {
await createFile(file, random)
const path = await createFile(file, random)
assert(path === normalize(file), `Should ${file} but result ${path}`)
}
catch (ex) {
return assert(false, ex)
Expand Down Expand Up @@ -149,7 +151,8 @@ describe(filename, () => {
const opts = { mode: 0o640 }

try {
await createFile(file, json, opts)
const path = await createFile(file, json, opts)
assert(path === normalize(file), `Should ${file} but result ${path}`)
}
catch (ex) {
return assert(false, ex)
Expand Down Expand Up @@ -179,7 +182,8 @@ describe(filename, () => {
const str = JSON.stringify(json)

try {
await createFile(file, json)
const path = await createFile(file, json)
assert(path === normalize(file), `Should ${file} but result ${path}`)
}
catch (ex) {
return assert(false, ex)
Expand Down

0 comments on commit 6ac4970

Please sign in to comment.