try-with
v0.2.0
Published
[![Build Status](https://travis-ci.org/levp/try-with.svg?branch=master)](https://travis-ci.org/levp/try-with)
Downloads
8
Maintainers
Readme
try-with
A utility for safe and convenient handling of managed resources in JavasScript.
The purpose of this utility is to provide a convenient and safe way of using resources that must be manually released, such as remote connections and file handlers.
Similar concepts:
- try-with-resource in Java
- using statement in C#.
Installing
npm: npm i try-with
yarn: yarn add try-with
Example
A potential resource leak due to stream not being closed:
const stream = fs.createWriteStream(filePath);
// Next line will throw if `data` is not one of the allowed types.
stream.write(data);
// Will never be called if previous line threw and someone caught the error.
stream.close();
A safe variant of the above code:
const stream = fs.createWriteStream(filePath);
try {
stream.write(data);
} finally {
stream.close();
}
Functionally equivalent to the code above but using try-with
:
const tryWith = require('try-with');
tryWith(fs.createWriteStream(filePath), stream => {
stream.write(data);
});
API
tryWith(object, action, [cleanupMethodOrName])
- Invokes
action
, passingobject
to it as a parameter. - After action is finished try to perform cleanup:
- If third argument was omitted:
- If
dispose
property exists onobject
, try to invoke it. - Else if
close
property exists onobject
, try to invoke it.
- If
- Else If third argument was provided and is a function, invoke it and pass
object
to it as a paramter. - Else (third argument was provided but is not a function):
- If it is a string or a symbol, try to invoke a property with that key on
object
. - Else convert third argument to string and try to invoke a property with that key on
object
.
- If it is a string or a symbol, try to invoke a property with that key on
- If third argument was omitted:
- If an error was thrown when
action
was invoked, rethrow it.
Building and Testing
npm run build
or npm run watch
to compile TypeScript.npm test
to run tests, make sure to compile before doing so.
License
ISC