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#.
npm: npm i try-with
yarn: yarn add try-with
A potential resource leak due to stream not being closed:
conststream=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:
conststream=fs.createWriteStream(filePath);try{stream.write(data);}finally{stream.close();}Functionally equivalent to the code above but using try-with:
consttryWith=require('try-with');tryWith(fs.createWriteStream(filePath),stream=>{stream.write(data);});tryWith(object, action, [cleanupMethodOrName])
- Invokes
action, passingobjectto it as a parameter. - After action is finished try to perform cleanup:
- If third argument was omitted:
- If
disposeproperty exists onobject, try to invoke it. - Else if
closeproperty exists onobject, try to invoke it.
- If
- Else If third argument was provided and is a function, invoke it and pass
objectto 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
actionwas invoked, rethrow it.
npm run build or npm run watch to compile TypeScript.npm test to run tests, make sure to compile before doing so.
ISC