Skip to content

Instantly share code, notes, and snippets.

@ChristianRich
Created October 23, 2022 23:21
Show Gist options
  • Save ChristianRich/f5ce6c54b9c21808c5694691a672cfbd to your computer and use it in GitHub Desktop.
Save ChristianRich/f5ce6c54b9c21808c5694691a672cfbd to your computer and use it in GitHub Desktop.
Node.js read/write file promise wrapper
import fs from 'fs';
import path from 'path';
export const write = (
data: string,
filename: string,
dir: string = process.cwd(),
): Promise<string> =>
new Promise((resolve, reject) => {
const dest = path.resolve(`${dir}/${filename}`);
console.log(`Write to ${dest}`);
fs.writeFile(dest, data, err => {
if (err) {
return reject(err);
}
resolve(data.toString());
});
});
export const read = (
filename: string,
dir: string = process.cwd(),
): Promise<string> =>
new Promise((resolve, reject) => {
const dest = path.resolve(`${dir}/${filename}`);
console.log(`Read from ${dest}`);
fs.readFile(dest, (err, data) => {
if (err) {
return reject(err);
}
resolve(data.toString());
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment