-
-
Save ChristianRich/f5ce6c54b9c21808c5694691a672cfbd to your computer and use it in GitHub Desktop.
Node.js read/write file promise wrapper
This file contains hidden or 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'; | |
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