import * as fs from "fs"; import { promisify } from "util"; const content: Promise<string> = promisify(fs.readFile)("path/to/the/file", { encoding: "UTF-8" })
I am tired of looking that up over and over every time I want to read a file into a promise in Node using TypeScript, so here it is. Next time, bring me here, Google.
The promisify
call turns fs.readFile
from a callback-based method to a promise-based one. promisify
accepts a callback-based function as an argument, and returns a promise-based function. Then we call that promise-based function with the filepath and options, including the encoding.
If you forget to give it the encoding, then you get a Buffer
back instead of a string
.