Skip to content

Instantly share code, notes, and snippets.

@lski
Created March 17, 2020 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lski/0532b4c997290fde53716ce770145a1c to your computer and use it in GitHub Desktop.
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
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);
});
});
};
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