Created
March 17, 2020 12:55
-
-
Save lski/0532b4c997290fde53716ce770145a1c to your computer and use it in GitHub Desktop.
A simple check to see if a file exists, resolving to true or false, but creating the file regardless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
/** | |
* Accepts a full file path and checks whether the file exists returning the answer | |
* If it doesnt exist it will also attempt to create the file. | |
* | |
* @param {string} filepath The file to check and create. | |
*/ | |
export const fileExistsAndCreate = filepath => { | |
return new Promise((resolve, reject) => { | |
fs.open(filepath, 'wx', (err, fd) => { | |
if (err) { | |
if (err.code === 'EEXIST') { | |
resolve(true); | |
return; | |
} | |
reject(err); | |
return; | |
} | |
resolve(false); | |
// writeMyData(fd); | |
}); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
import path from 'path'; | |
import { fileExistsAndCreate } from './fileExistsAndCreate'; | |
test('File exists', async () => { | |
const filepath = path.join(__dirname, 'fileExists.test.js'); | |
const exists = await fileExistsAndCreate(filepath); | |
expect(exists).toBe(true); | |
}); | |
test('File didnt exist but is created', async () => { | |
const filepath = path.join(__dirname, 'an-other-file.txt'); | |
const originallyExists = await fileExistsAndCreate(filepath); | |
const nowExists = fs.existsSync(filepath); | |
fs.unlinkSync(filepath); | |
expect(originallyExists).toBe(false); | |
expect(nowExists).toBe(true); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment