Reputation: 11937
What's the best way to use TypeScript async/await with Node core api (fs, process, etc.)?
Converting a core module to use Promises with bluebird.promisifyAll()
would be perfect, except that way you lose type information and I'd like to able to keep that. You end up with xxxAsync method names and TypeScript typing system has no idea of their existence.
Is there a project that would have converted the core API to return promises and have TypeScript definition files .d.ts
to support it?
Upvotes: 0
Views: 297
Reputation: 1835
I think this is the better way:
// Example: checking file existence
let res = await new Promise((resolve, reject) => {
fs.access(filePath, fs.constants.R_OK, async (err) => {
if (err) {
console.error('File does not exists or cannot be read');
return resolve(false);
}
return resolve(true);
});
});
console.log(res); // Correctly resolved (true/false)
Upvotes: 0
Reputation: 1824
Checkout the async-file wrapper on NPM. It's a drop-in replacement for fs that wraps all the async functions in a Promise, and provides strong typing. It also provides some convenience functions to simplify accessing text files and deleting files and directories.
Upvotes: 2