diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml
new file mode 100644
index 0000000..dbced9a
--- /dev/null
+++ b/.github/workflows/node.js.yml
@@ -0,0 +1,32 @@
+# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
+
+name: Node.js CI
+
+on:
+ push:
+ branches: [ "master" ]
+ pull_request:
+ branches: [ "master" ]
+
+jobs:
+ build:
+
+ strategy:
+ matrix:
+ node-version: [14.x, 16.x, 18.x, 20.x]
+ os: [ubuntu-latest, windows-latest]
+ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
+
+ runs-on: ${{ matrix.os }}
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Use Node.js ${{ matrix.node-version }}
+ uses: actions/setup-node@v3
+ with:
+ node-version: ${{ matrix.node-version }}
+ cache: 'npm'
+ - run: npm ci
+ # - run: npm run build --if-present
+ - run: npm test
diff --git a/.gitignore b/.gitignore
index 7290036..014f812 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,10 @@
node_modules/
coverage/
+.env
.idea/
+.tool-versions
.*.swp
-package-lock.json
+.changelog
+CHANGELOG.new.md
+CHANGELOG.add.md
+CHANGELOG.new.md.tmp
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index f3dde6f..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-language: node_js
-node_js:
- - "node"
- - "10"
- - "9"
- - "8"
-sudo: false
-cache:
- directories:
- - node_modules
-before_install:
- # Update Node.js modules
- - "test ! -d node_modules || npm prune"
- - "test ! -d node_modules || npm rebuild"
-addons:
- code_climate:
- repo_token: ca200a6930ee90adbc4192a3bdb9f60dccdae00cb78f9880a2841d6b
-after_success:
- - npm install --save-dev codeclimate-test-reporter
- - codeclimate-test-reporter < coverage/lcov.info
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..0cdbc6b
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,304 @@
+
+
+## v0.2.2 (2024-02-28)
+
+#### :bug: Bug Fix
+* [#278](https://github.com/raszi/node-tmp/pull/278) Closes [#268](https://github.com/raszi/node-tmp/issues/268): Revert "fix #246: remove any double quotes or single quotes… ([@mbargiel](https://github.com/mbargiel))
+
+#### :memo: Documentation
+* [#279](https://github.com/raszi/node-tmp/pull/279) Closes [#266](https://github.com/raszi/node-tmp/issues/266): move paragraph on graceful cleanup to the head of the documentation ([@silkentrance](https://github.com/silkentrance))
+
+#### Committers: 5
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- Dave Nicolson ([@dnicolson](https://github.com/dnicolson))
+- KARASZI István ([@raszi](https://github.com/raszi))
+- Maxime Bargiel ([@mbargiel](https://github.com/mbargiel))
+- [@robertoaceves](https://github.com/robertoaceves)
+
+
+## v0.2.1 (2020-04-28)
+
+#### :rocket: Enhancement
+* [#252](https://github.com/raszi/node-tmp/pull/252) Closes [#250](https://github.com/raszi/node-tmp/issues/250): introduce tmpdir option for overriding the system tmp dir ([@silkentrance](https://github.com/silkentrance))
+
+#### :house: Internal
+* [#253](https://github.com/raszi/node-tmp/pull/253) Closes [#191](https://github.com/raszi/node-tmp/issues/191): generate changelog from pull requests using lerna-changelog ([@silkentrance](https://github.com/silkentrance))
+
+#### Committers: 1
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+
+
+## v0.2.0 (2020-04-25)
+
+#### :rocket: Enhancement
+* [#234](https://github.com/raszi/node-tmp/pull/234) feat: stabilize tmp for v0.2.0 release ([@silkentrance](https://github.com/silkentrance))
+
+#### :bug: Bug Fix
+* [#231](https://github.com/raszi/node-tmp/pull/231) Closes [#230](https://github.com/raszi/node-tmp/issues/230): regression after fix for #197 ([@silkentrance](https://github.com/silkentrance))
+* [#220](https://github.com/raszi/node-tmp/pull/220) Closes [#197](https://github.com/raszi/node-tmp/issues/197): return sync callback when using the sync interface, otherwise return the async callback ([@silkentrance](https://github.com/silkentrance))
+* [#193](https://github.com/raszi/node-tmp/pull/193) Closes [#192](https://github.com/raszi/node-tmp/issues/192): tmp must not exit the process on its own ([@silkentrance](https://github.com/silkentrance))
+
+#### :memo: Documentation
+* [#221](https://github.com/raszi/node-tmp/pull/221) Gh 206 document name option ([@silkentrance](https://github.com/silkentrance))
+
+#### :house: Internal
+* [#226](https://github.com/raszi/node-tmp/pull/226) Closes [#212](https://github.com/raszi/node-tmp/issues/212): enable direct name option test ([@silkentrance](https://github.com/silkentrance))
+* [#225](https://github.com/raszi/node-tmp/pull/225) Closes [#211](https://github.com/raszi/node-tmp/issues/211): existing tests must clean up after themselves ([@silkentrance](https://github.com/silkentrance))
+* [#224](https://github.com/raszi/node-tmp/pull/224) Closes [#217](https://github.com/raszi/node-tmp/issues/217): name tests must use tmpName ([@silkentrance](https://github.com/silkentrance))
+* [#223](https://github.com/raszi/node-tmp/pull/223) Closes [#214](https://github.com/raszi/node-tmp/issues/214): refactor tests and lib ([@silkentrance](https://github.com/silkentrance))
+* [#198](https://github.com/raszi/node-tmp/pull/198) Update dependencies to latest versions ([@matsev](https://github.com/matsev))
+
+#### Committers: 2
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- Mattias Severson ([@matsev](https://github.com/matsev))
+
+
+## v0.1.0 (2019-03-20)
+
+#### :rocket: Enhancement
+* [#177](https://github.com/raszi/node-tmp/pull/177) fix: fail early if there is no tmp dir specified ([@silkentrance](https://github.com/silkentrance))
+* [#159](https://github.com/raszi/node-tmp/pull/159) Closes [#121](https://github.com/raszi/node-tmp/issues/121) ([@silkentrance](https://github.com/silkentrance))
+* [#161](https://github.com/raszi/node-tmp/pull/161) Closes [#155](https://github.com/raszi/node-tmp/issues/155) ([@silkentrance](https://github.com/silkentrance))
+* [#166](https://github.com/raszi/node-tmp/pull/166) fix: avoid relying on Node’s internals ([@addaleax](https://github.com/addaleax))
+* [#144](https://github.com/raszi/node-tmp/pull/144) prepend opts.dir || tmpDir to template if no path is given ([@silkentrance](https://github.com/silkentrance))
+
+#### :bug: Bug Fix
+* [#183](https://github.com/raszi/node-tmp/pull/183) Closes [#182](https://github.com/raszi/node-tmp/issues/182) fileSync takes empty string postfix option ([@gutte](https://github.com/gutte))
+* [#130](https://github.com/raszi/node-tmp/pull/130) Closes [#129](https://github.com/raszi/node-tmp/issues/129) install process listeners safely ([@silkentrance](https://github.com/silkentrance))
+
+#### :memo: Documentation
+* [#188](https://github.com/raszi/node-tmp/pull/188) HOTCloses [#187](https://github.com/raszi/node-tmp/issues/187): restore behaviour for #182 ([@silkentrance](https://github.com/silkentrance))
+* [#180](https://github.com/raszi/node-tmp/pull/180) fix gh-179: template no longer accepts arbitrary paths ([@silkentrance](https://github.com/silkentrance))
+* [#175](https://github.com/raszi/node-tmp/pull/175) docs: add `unsafeCleanup` option to jsdoc ([@kerimdzhanov](https://github.com/kerimdzhanov))
+* [#151](https://github.com/raszi/node-tmp/pull/151) docs: fix link to tmp-promise ([@silkentrance](https://github.com/silkentrance))
+
+#### :house: Internal
+* [#184](https://github.com/raszi/node-tmp/pull/184) test: add missing tests for #182 ([@silkentrance](https://github.com/silkentrance))
+* [#171](https://github.com/raszi/node-tmp/pull/171) chore: drop old NodeJS support ([@poppinlp](https://github.com/poppinlp))
+* [#170](https://github.com/raszi/node-tmp/pull/170) chore: update dependencies ([@raszi](https://github.com/raszi))
+* [#165](https://github.com/raszi/node-tmp/pull/165) test: add missing tests ([@raszi](https://github.com/raszi))
+* [#163](https://github.com/raszi/node-tmp/pull/163) chore: add lint npm task ([@raszi](https://github.com/raszi))
+* [#107](https://github.com/raszi/node-tmp/pull/107) chore: add coverage report ([@raszi](https://github.com/raszi))
+* [#141](https://github.com/raszi/node-tmp/pull/141) test: refactor tests for mocha ([@silkentrance](https://github.com/silkentrance))
+* [#154](https://github.com/raszi/node-tmp/pull/154) chore: change Travis configuration ([@raszi](https://github.com/raszi))
+* [#152](https://github.com/raszi/node-tmp/pull/152) fix: drop Node v0.6.0 ([@raszi](https://github.com/raszi))
+
+#### Committers: 6
+- Anna Henningsen ([@addaleax](https://github.com/addaleax))
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- Dan Kerimdzhanov ([@kerimdzhanov](https://github.com/kerimdzhanov))
+- Gustav Klingstedt ([@gutte](https://github.com/gutte))
+- KARASZI István ([@raszi](https://github.com/raszi))
+- PoppinL ([@poppinlp](https://github.com/poppinlp))
+
+
+## v0.0.33 (2017-08-12)
+
+#### :rocket: Enhancement
+* [#147](https://github.com/raszi/node-tmp/pull/147) fix: with name option try at most once to get a unique tmp name ([@silkentrance](https://github.com/silkentrance))
+
+#### :bug: Bug Fix
+* [#149](https://github.com/raszi/node-tmp/pull/149) fix(fileSync): must honor detachDescriptor and discardDescriptor options ([@silkentrance](https://github.com/silkentrance))
+* [#119](https://github.com/raszi/node-tmp/pull/119) Closes [#115](https://github.com/raszi/node-tmp/issues/115) ([@silkentrance](https://github.com/silkentrance))
+
+#### :memo: Documentation
+* [#128](https://github.com/raszi/node-tmp/pull/128) Closes [#127](https://github.com/raszi/node-tmp/issues/127) add reference to tmp-promise ([@silkentrance](https://github.com/silkentrance))
+
+#### :house: Internal
+* [#135](https://github.com/raszi/node-tmp/pull/135) Closes [#133](https://github.com/raszi/node-tmp/issues/133), #134 ([@silkentrance](https://github.com/silkentrance))
+* [#123](https://github.com/raszi/node-tmp/pull/123) docs: update tmp.js MIT license header to 2017 ([@madnight](https://github.com/madnight))
+* [#122](https://github.com/raszi/node-tmp/pull/122) chore: add issue template ([@silkentrance](https://github.com/silkentrance))
+
+#### Committers: 2
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- Fabian Beuke ([@madnight](https://github.com/madnight))
+
+
+## v0.0.32 (2017-03-24)
+
+#### :memo: Documentation
+* [#106](https://github.com/raszi/node-tmp/pull/106) doc: add proper JSDoc documentation ([@raszi](https://github.com/raszi))
+
+#### :house: Internal
+* [#111](https://github.com/raszi/node-tmp/pull/111) test: add Windows tests ([@binki](https://github.com/binki))
+* [#110](https://github.com/raszi/node-tmp/pull/110) chore: add AppVeyor ([@binki](https://github.com/binki))
+* [#105](https://github.com/raszi/node-tmp/pull/105) chore: use const where possible ([@raszi](https://github.com/raszi))
+* [#104](https://github.com/raszi/node-tmp/pull/104) style: fix various style issues ([@raszi](https://github.com/raszi))
+
+#### Committers: 2
+- KARASZI István ([@raszi](https://github.com/raszi))
+- Nathan Phillip Brink ([@binki](https://github.com/binki))
+
+
+## v0.0.31 (2016-11-21)
+
+#### :rocket: Enhancement
+* [#99](https://github.com/raszi/node-tmp/pull/99) feat: add next callback functionality ([@silkentrance](https://github.com/silkentrance))
+* [#94](https://github.com/raszi/node-tmp/pull/94) feat: add options to control descriptor management ([@pabigot](https://github.com/pabigot))
+
+#### :house: Internal
+* [#101](https://github.com/raszi/node-tmp/pull/101) fix: Include files in the package.json ([@raszi](https://github.com/raszi))
+
+#### Committers: 3
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- KARASZI István ([@raszi](https://github.com/raszi))
+- Peter A. Bigot ([@pabigot](https://github.com/pabigot))
+
+
+## v0.0.30 (2016-11-01)
+
+#### :bug: Bug Fix
+* [#96](https://github.com/raszi/node-tmp/pull/96) fix: constants for Node 6 ([@jnj16180340](https://github.com/jnj16180340))
+* [#98](https://github.com/raszi/node-tmp/pull/98) fix: garbage collector ([@Ari-H](https://github.com/Ari-H))
+
+#### Committers: 2
+- Nate Johnson ([@jnj16180340](https://github.com/jnj16180340))
+- [@Ari-H](https://github.com/Ari-H)
+
+
+## v0.0.29 (2016-09-18)
+
+#### :rocket: Enhancement
+* [#87](https://github.com/raszi/node-tmp/pull/87) fix: replace calls to deprecated fs API functions ([@OlliV](https://github.com/OlliV))
+
+#### :bug: Bug Fix
+* [#70](https://github.com/raszi/node-tmp/pull/70) fix: prune `_removeObjects` correctly ([@joliss](https://github.com/joliss))
+* [#71](https://github.com/raszi/node-tmp/pull/71) Fix typo ([@gcampax](https://github.com/gcampax))
+
+#### :memo: Documentation
+* [#77](https://github.com/raszi/node-tmp/pull/77) docs: change mkstemps to mkstemp ([@thefourtheye](https://github.com/thefourtheye))
+
+#### :house: Internal
+* [#92](https://github.com/raszi/node-tmp/pull/92) chore: add Travis CI support for Node 6 ([@amilajack](https://github.com/amilajack))
+* [#79](https://github.com/raszi/node-tmp/pull/79) fix: remove unneeded require statement ([@whmountains](https://github.com/whmountains))
+
+#### Committers: 6
+- Amila Welihinda ([@amilajack](https://github.com/amilajack))
+- Caleb Whiting ([@whmountains](https://github.com/whmountains))
+- Giovanni Campagna ([@gcampax](https://github.com/gcampax))
+- Jo Liss ([@joliss](https://github.com/joliss))
+- Olli Vanhoja ([@OlliV](https://github.com/OlliV))
+- Sakthipriyan Vairamani ([@thefourtheye](https://github.com/thefourtheye))
+
+
+## v0.0.28 (2015-09-27)
+
+#### :bug: Bug Fix
+* [#63](https://github.com/raszi/node-tmp/pull/63) fix: delete for _rmdirRecursiveSync ([@voltrevo](https://github.com/voltrevo))
+
+#### :memo: Documentation
+* [#64](https://github.com/raszi/node-tmp/pull/64) docs: fix typo in the README ([@JTKnox91](https://github.com/JTKnox91))
+
+#### :house: Internal
+* [#67](https://github.com/raszi/node-tmp/pull/67) test: add node v4.0 v4.1 to travis config ([@raszi](https://github.com/raszi))
+* [#66](https://github.com/raszi/node-tmp/pull/66) chore(deps): update deps ([@raszi](https://github.com/raszi))
+
+#### Committers: 3
+- Andrew Morris ([@voltrevo](https://github.com/voltrevo))
+- John T. Knox ([@JTKnox91](https://github.com/JTKnox91))
+- KARASZI István ([@raszi](https://github.com/raszi))
+
+
+## v0.0.27 (2015-08-15)
+
+#### :bug: Bug Fix
+* [#60](https://github.com/raszi/node-tmp/pull/60) fix: unlinking when the file has been already removed ([@silkentrance](https://github.com/silkentrance))
+
+#### :memo: Documentation
+* [#55](https://github.com/raszi/node-tmp/pull/55) docs(README): update README ([@raszi](https://github.com/raszi))
+
+#### :house: Internal
+* [#56](https://github.com/raszi/node-tmp/pull/56) style(jshint): fix JSHint error ([@raszi](https://github.com/raszi))
+* [#53](https://github.com/raszi/node-tmp/pull/53) chore: update license attribute ([@pdehaan](https://github.com/pdehaan))
+
+#### Committers: 3
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- KARASZI István ([@raszi](https://github.com/raszi))
+- Peter deHaan ([@pdehaan](https://github.com/pdehaan))
+
+
+## v0.0.26 (2015-05-12)
+
+#### :rocket: Enhancement
+* [#40](https://github.com/raszi/node-tmp/pull/40) Fix for #39 ([@silkentrance](https://github.com/silkentrance))
+* [#42](https://github.com/raszi/node-tmp/pull/42) Fix for #17 ([@silkentrance](https://github.com/silkentrance))
+* [#41](https://github.com/raszi/node-tmp/pull/41) Fix for #37 ([@silkentrance](https://github.com/silkentrance))
+* [#32](https://github.com/raszi/node-tmp/pull/32) add ability to customize file/dir names ([@shime](https://github.com/shime))
+* [#29](https://github.com/raszi/node-tmp/pull/29) tmp.file have responsibility to close file, not only unlink file ([@vhain](https://github.com/vhain))
+
+#### :bug: Bug Fix
+* [#51](https://github.com/raszi/node-tmp/pull/51) fix(windows): fix tempDir on windows ([@raszi](https://github.com/raszi))
+* [#49](https://github.com/raszi/node-tmp/pull/49) remove object from _removeObjects if cleanup fn is called Closes [#48](https://github.com/raszi/node-tmp/issues/48) ([@bmeck](https://github.com/bmeck))
+
+#### :memo: Documentation
+* [#45](https://github.com/raszi/node-tmp/pull/45) Fix for #44 ([@silkentrance](https://github.com/silkentrance))
+
+#### :house: Internal
+* [#34](https://github.com/raszi/node-tmp/pull/34) Create LICENSE ([@ScottWeinstein](https://github.com/ScottWeinstein))
+
+#### Committers: 6
+- Bradley Farias ([@bmeck](https://github.com/bmeck))
+- Carsten Klein ([@silkentrance](https://github.com/silkentrance))
+- Hrvoje Šimić ([@shime](https://github.com/shime))
+- Juwan Yoo ([@vhain](https://github.com/vhain))
+- KARASZI István ([@raszi](https://github.com/raszi))
+- Scott Weinstein ([@ScottWeinstein](https://github.com/ScottWeinstein))
+
+
+## v0.0.24 (2014-07-11)
+
+#### :rocket: Enhancement
+* [#25](https://github.com/raszi/node-tmp/pull/25) Added removeCallback passing ([@foxel](https://github.com/foxel))
+
+#### Committers: 1
+- Andrey Kupreychik ([@foxel](https://github.com/foxel))
+
+
+## v0.0.23 (2013-12-03)
+
+#### :rocket: Enhancement
+* [#21](https://github.com/raszi/node-tmp/pull/21) If we are not on node 0.8, don't register an uncaughtException handler ([@wibblymat](https://github.com/wibblymat))
+
+#### Committers: 1
+- Mat Scales ([@wibblymat](https://github.com/wibblymat))
+
+
+## v0.0.22 (2013-11-29)
+
+#### :rocket: Enhancement
+* [#19](https://github.com/raszi/node-tmp/pull/19) Rethrow only on node v0.8. ([@mcollina](https://github.com/mcollina))
+
+#### Committers: 1
+- Matteo Collina ([@mcollina](https://github.com/mcollina))
+
+
+## v0.0.21 (2013-08-07)
+
+#### :bug: Bug Fix
+* [#16](https://github.com/raszi/node-tmp/pull/16) Fix bug where we delete contents of symlinks ([@lightsofapollo](https://github.com/lightsofapollo))
+
+#### Committers: 1
+- James Lal ([@lightsofapollo](https://github.com/lightsofapollo))
+
+
+## v0.0.17 (2013-04-09)
+
+#### :rocket: Enhancement
+* [#9](https://github.com/raszi/node-tmp/pull/9) add recursive remove option ([@oscar-broman](https://github.com/oscar-broman))
+
+#### Committers: 1
+- [@oscar-broman](https://github.com/oscar-broman)
+
+
+## v0.0.14 (2012-08-26)
+
+#### :rocket: Enhancement
+* [#5](https://github.com/raszi/node-tmp/pull/5) Export _getTmpName for temporary file name creation ([@joscha](https://github.com/joscha))
+
+#### Committers: 1
+- Joscha Feth ([@joscha](https://github.com/joscha))
+
+
+## Previous Releases < v0.0.14
+
+- no information available
diff --git a/README.md b/README.md
index 859a3d7..976ac9b 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
A simple temporary file and directory creator for [node.js.][1]
-[](https://travis-ci.org/raszi/node-tmp)
-[](https://david-dm.org/raszi/node-tmp)
+[](https://github.com/raszi/node-tmp/actions/workflows/node.js.yml)
+[](https://libraries.io/github/raszi/node-tmp)
[](https://badge.fury.io/js/tmp)
[](https://raszi.github.io/node-tmp/)
[](https://snyk.io/test/npm/tmp)
@@ -27,8 +27,41 @@ not.
If you do not want to store your temporary directories and files in the
standard OS temporary directory, then you are free to override that as well.
+## An Important Note on Previously Undocumented Breaking Changes
+
+All breaking changes that had been introduced, i.e.
+
+- tmpdir must be located under the system defined tmpdir root.
+- Spaces being collapsed into single spaces
+- Removal of all single and double quote characters
+
+have been reverted in v0.2.2 and tmp should now behave as it did before the
+introduction of these breaking changes.
+
+Other breaking changes, i.e.
+
+- template must be relative to tmpdir
+- name must be relative to tmpdir
+- dir option must be relative to tmpdir
+
+are still in place.
+
+In order to override the system's tmpdir, you will have to use the newly
+introduced tmpdir option.
+
## An Important Note on Compatibility
+See the [CHANGELOG](./CHANGELOG.md) for more information.
+
+### Version 0.2.3
+
+- Node version <= 14.4 has been dropped.
+- rimraf has been dropped from the dependencies
+
+### Version 0.2.2
+
+Since version 0.2.2, all support for node version <= 14 has been dropped.
+
### Version 0.1.0
Since version 0.1.0, all support for node versions < 0.10.0 has been dropped.
@@ -48,15 +81,6 @@ dependency to version 0.0.33.
For node versions < 0.8 you must limit your node-tmp dependency to
versions < 0.0.33.
-### Node Versions < 8.12.0
-
-The SIGINT handler will not work correctly with versions of NodeJS < 8.12.0.
-
-### Windows
-
-Signal handlers for SIGINT will not work. Pressing CTRL-C will leave behind
-temporary files and directories.
-
## How to install
```bash
@@ -67,12 +91,24 @@ npm install tmp
Please also check [API docs][4].
+## Graceful cleanup
+
+If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary object removal.
+
+To enforce this, you can call the `setGracefulCleanup()` method:
+
+```javascript
+const tmp = require('tmp');
+
+tmp.setGracefulCleanup();
+```
+
### Asynchronous file creation
Simple temporary file creation, the file will be closed and unlinked on process exit.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
@@ -92,9 +128,9 @@ tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
A synchronous version of the above.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var tmpobj = tmp.fileSync();
+const tmpobj = tmp.fileSync();
console.log('File: ', tmpobj.name);
console.log('Filedescriptor: ', tmpobj.fd);
@@ -115,7 +151,7 @@ Simple temporary directory creation, it will be removed on process exit.
If the directory still contains items on process exit, then it won't be removed.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.dir(function _tempDirCreated(err, path, cleanupCallback) {
if (err) throw err;
@@ -135,9 +171,9 @@ you can pass the `unsafeCleanup` option when creating it.
A synchronous version of the above.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var tmpobj = tmp.dirSync();
+const tmpobj = tmp.dirSync();
console.log('Dir: ', tmpobj.name);
// Manual cleanup
tmpobj.removeCallback();
@@ -153,7 +189,7 @@ It is possible with this library to generate a unique filename in the specified
directory.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.tmpName(function _tempNameGenerated(err, path) {
if (err) throw err;
@@ -167,9 +203,9 @@ tmp.tmpName(function _tempNameGenerated(err, path) {
A synchronous version of the above.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var name = tmp.tmpNameSync();
+const name = tmp.tmpNameSync();
console.log('Created temporary filename: ', name);
```
@@ -180,9 +216,9 @@ console.log('Created temporary filename: ', name);
Creates a file with mode `0644`, prefix will be `prefix-` and postfix will be `.txt`.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-tmp.file({ mode: 0644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileCreated(err, path, fd) {
+tmp.file({ mode: 0o644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileCreated(err, path, fd) {
if (err) throw err;
console.log('File: ', path);
@@ -195,9 +231,9 @@ tmp.file({ mode: 0644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileC
A synchronous version of the above.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var tmpobj = tmp.fileSync({ mode: 0644, prefix: 'prefix-', postfix: '.txt' });
+const tmpobj = tmp.fileSync({ mode: 0o644, prefix: 'prefix-', postfix: '.txt' });
console.log('File: ', tmpobj.name);
console.log('Filedescriptor: ', tmpobj.fd);
```
@@ -219,7 +255,7 @@ descriptor. Two options control how the descriptor is managed:
longer needed.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
@@ -229,7 +265,7 @@ tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, c
```
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.file({ detachDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
@@ -246,9 +282,9 @@ tmp.file({ detachDescriptor: true }, function _tempFileCreated(err, path, fd, cl
Creates a directory with mode `0755`, prefix will be `myTmpDir_`.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-tmp.dir({ mode: 0750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path) {
+tmp.dir({ mode: 0o750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path) {
if (err) throw err;
console.log('Dir: ', path);
@@ -260,9 +296,9 @@ tmp.dir({ mode: 0750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path)
Again, a synchronous version of the above.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var tmpobj = tmp.dirSync({ mode: 0750, prefix: 'myTmpDir_' });
+const tmpobj = tmp.dirSync({ mode: 0750, prefix: 'myTmpDir_' });
console.log('Dir: ', tmpobj.name);
```
@@ -275,7 +311,7 @@ require tmp to create your temporary filesystem object in a different place than
default `tmp.tmpdir`.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
tmp.dir({ template: 'tmp-XXXXXX' }, function _tempDirCreated(err, path) {
if (err) throw err;
@@ -289,9 +325,9 @@ tmp.dir({ template: 'tmp-XXXXXX' }, function _tempDirCreated(err, path) {
This will behave similarly to the asynchronous version.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var tmpobj = tmp.dirSync({ template: 'tmp-XXXXXX' });
+const tmpobj = tmp.dirSync({ template: 'tmp-XXXXXX' });
console.log('Dir: ', tmpobj.name);
```
@@ -303,9 +339,9 @@ The function accepts all standard options, e.g. `prefix`, `postfix`, `dir`, and
You can also leave out the options altogether and just call the function with a callback as first parameter.
```javascript
-var tmp = require('tmp');
+const tmp = require('tmp');
-var options = {};
+const options = {};
tmp.tmpName(options, function _tempNameGenerated(err, path) {
if (err) throw err;
@@ -320,36 +356,33 @@ The `tmpNameSync()` function works similarly to `tmpName()`.
Again, you can leave out the options altogether and just invoke the function without any parameters.
```javascript
-var tmp = require('tmp');
-var options = {};
-var tmpname = tmp.tmpNameSync(options);
+const tmp = require('tmp');
+const options = {};
+const tmpname = tmp.tmpNameSync(options);
console.log('Created temporary filename: ', tmpname);
```
-## Graceful cleanup
-
-One may want to cleanup the temporary files even when an uncaught exception
-occurs. To enforce this, you can call the `setGracefulCleanup()` method:
-
-```javascript
-var tmp = require('tmp');
-
-tmp.setGracefulCleanup();
-```
-
## Options
All options are optional :)
- * `mode`: the file mode to create with, it fallbacks to `0600` on file creation and `0700` on directory creation
- * `prefix`: the optional prefix, fallbacks to `tmp-` if not provided
- * `postfix`: the optional postfix, fallbacks to `.tmp` on file creation
- * `template`: [`mkstemp`][3] like filename template, no default
- * `dir`: the optional temporary directory, fallbacks to system default (guesses from environment)
+ * `name`: a fixed name that overrides random name generation, the name must be relative and must not contain path segments
+ * `mode`: the file mode to create with, falls back to `0o600` on file creation and `0o700` on directory creation
+ * `prefix`: the optional prefix, defaults to `tmp`
+ * `postfix`: the optional postfix
+ * `template`: [`mkstemp`][3] like filename template, no default, must include `XXXXXX` once for random name generation, e.g.
+ 'foo-bar-XXXXXX'.
+ * `dir`: the optional temporary directory that must be relative to the system's default temporary directory.
+ absolute paths are fine as long as they point to a location under the system's default temporary directory.
+ Any directories along the so specified path must exist, otherwise a ENOENT error will be thrown upon access,
+ as tmp will not check the availability of the path, nor will it establish the requested path for you.
+ * `tmpdir`: allows you to override the system's root tmp directory
* `tries`: how many times should the function try to get a unique filename before giving up, default `3`
* `keep`: signals that the temporary file or directory should not be deleted on exit, default is `false`
* In order to clean up, you will have to call the provided `cleanupCallback` function manually.
* `unsafeCleanup`: recursively removes the created temporary directory, even when it's not empty. default is `false`
+ * `detachDescriptor`: detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection
+ * `discardDescriptor`: discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection
[1]: http://nodejs.org/
[2]: https://www.npmjs.com/browse/depended/tmp
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 743d881..0000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-# https://www.appveyor.com/docs/lang/nodejs-iojs/
-
-environment:
- matrix:
- - nodejs_version: "7"
- - nodejs_version: "8"
- - nodejs_version: "9"
- - nodejs_version: "10"
- - nodejs_version: "11"
-
-install:
- - ps: Install-Product node $env:nodejs_version
- - npm install
-
-test_script:
- - node --version
- - npm --version
- - npm test
-
-build: off
diff --git a/docs/global.html b/docs/global.html
index 820fcd7..22766d4 100644
--- a/docs/global.html
+++ b/docs/global.html
@@ -87,42 +87,6 @@
Sets the graceful cleanup.
-Also removes the created files and directories when an uncaught exception occurs.
+If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the
+temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary
+object removals.
Tmp offers both an asynchronous and a synchronous API. For all API calls, all
-the parameters are optional.
+the parameters are optional. There also exists a promisified version of the
+API, see tmp-promise.
Tmp uses crypto for determining random file names, or, when using templates,
a six letter random identifier. And just in case that you do not have that much
entropy left on your system, Tmp will fall back to pseudo random numbers.
You can set whether you want to remove the temporary file on process exit or
-not, and the destination directory can also be set.
-
How to install
npm install tmp
Usage
Asynchronous file creation
Simple temporary file creation, the file will be closed and unlinked on process exit.
-
var tmp = require('tmp');
+not.
+
If you do not want to store your temporary directories and files in the
+standard OS temporary directory, then you are free to override that as well.
+
An Important Note on Previously Undocumented Breaking Changes
+
All breaking changes that had been introduced, i.e.
+
+
tmpdir must be located under the system defined tmpdir root.
+
Spaces being collapsed into single spaces
+
Removal of all single and double quote characters
+
+
have been reverted in v0.2.2 and tmp should now behave as it did before the
+introduction of these breaking changes.
+
Other breaking changes, i.e.
+
+
template must be relative to tmpdir
+
name must be relative to tmpdir
+
dir option must be relative to tmpdir
+
+
are still in place.
+
In order to override the system's tmpdir, you will have to use the newly
+introduced tmpdir option.
If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary object removal.
+
To enforce this, you can call the setGracefulCleanup() method:
Simple temporary file creation, the file will be closed and unlinked on process exit.
+
const tmp = require('tmp');
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
- console.log("File: ", path);
- console.log("Filedescriptor: ", fd);
-
+ console.log('File: ', path);
+ console.log('Filedescriptor: ', fd);
+
// If we don't need the file anymore we could manually call the cleanupCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
cleanupCallback();
-});
const tmp = require('tmp');
+
+const tmpobj = tmp.fileSync();
+console.log('File: ', tmpobj.name);
+console.log('Filedescriptor: ', tmpobj.fd);
+
// If we don't need the file anymore we could manually call the removeCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
-tmpobj.removeCallback();
Note that this might throw an exception if either the maximum limit of retries
+tmpobj.removeCallback();
+
+
Note that this might throw an exception if either the maximum limit of retries
for creating a temporary name fails, or, in case that you do not have the permission
to write to the directory where the temporary file should be created in.
-
Asynchronous directory creation
Simple temporary directory creation, it will be removed on process exit.
+
Asynchronous directory creation
+
Simple temporary directory creation, it will be removed on process exit.
If the directory still contains items on process exit, then it won't be removed.
Note that this might throw an exception if either the maximum limit of retries
+tmpobj.removeCallback();
+
+
Note that this might throw an exception if either the maximum limit of retries
for creating a temporary name fails, or, in case that you do not have the permission
to write to the directory where the temporary directory should be created in.
-
Asynchronous filename generation
It is possible with this library to generate a unique filename in the specified
+
Asynchronous filename generation
+
It is possible with this library to generate a unique filename in the specified
directory.
As a side effect of creating a unique file tmp gets a file descriptor that is
+ console.log('File: ', path);
+ console.log('Filedescriptor: ', fd);
+});
+
As a side effect of creating a unique file tmp gets a file descriptor that is
returned to the user as the fd parameter. The descriptor may be used by the
application and is closed when the removeCallback is invoked.
In some use cases the application does not need the descriptor, needs to close it
@@ -143,13 +220,15 @@
Asynchronous filename generation
It is possible with this library to
parameter, but it is the application's responsibility to close it when it is no
longer needed.
-
var tmp = require('tmp');
+
const tmp = require('tmp');
tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
// fd will be undefined, allowing application to use fs.createReadStream(path)
// without holding an unused descriptor open.
-});
It is possible with this library to
// Application can store data through fd here; the space used will automatically
// be reclaimed by the operating system when the descriptor is closed or program
// terminates.
-});
Asynchronous directory creation
Creates a directory with mode 0755, prefix will be myTmpDir_.
-
var tmp = require('tmp');
+});
+
+
Asynchronous directory creation
+
Creates a directory with mode 0755, prefix will be myTmpDir_.
Creates a new temporary directory with mode 0700 and filename like /tmp/tmp-nk2J1u.
+
IMPORTANT NOTE: template no longer accepts a path. Use the dir option instead if you
+require tmp to create your temporary filesystem object in a different place than the
+default tmp.tmpdir.
The tmpNameSync() function works similarly to tmpName().
+Again, you can leave out the options altogether and just invoke the function without any parameters.
mode: the file mode to create with, it fallbacks to 0600 on file creation and 0700 on directory creation
-
prefix: the optional prefix, fallbacks to tmp- if not provided
-
postfix: the optional postfix, fallbacks to .tmp on file creation
-
template: mkstemp like filename template, no default
-
dir: the optional temporary directory, fallbacks to system default (guesses from environment)
+
name: a fixed name that overrides random name generation, the name must be relative and must not contain path segments
+
mode: the file mode to create with, falls back to 0o600 on file creation and 0o700 on directory creation
+
prefix: the optional prefix, defaults to tmp
+
postfix: the optional postfix
+
template: mkstemp like filename template, no default, must include XXXXXX once for random name generation, e.g.
+'foo-bar-XXXXXX'.
+
dir: the optional temporary directory that must be relative to the system's default temporary directory.
+absolute paths are fine as long as they point to a location under the system's default temporary directory.
+Any directories along the so specified path must exist, otherwise a ENOENT error will be thrown upon access,
+as tmp will not check the availability of the path, nor will it establish the requested path for you.
+
tmpdir: allows you to override the system's root tmp directory
tries: how many times should the function try to get a unique filename before giving up, default 3
-
keep: signals that the temporary file or directory should not be deleted on exit, default is false, means delete
-
Please keep in mind that it is recommended in this case to call the provided cleanupCallback function manually.
+
keep: signals that the temporary file or directory should not be deleted on exit, default is false
+
+
In order to clean up, you will have to call the provided cleanupCallback function manually.
unsafeCleanup: recursively removes the created temporary directory, even when it's not empty. default is false
+
detachDescriptor: detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection
+
discardDescriptor: discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection
@@ -218,13 +332,13 @@
Asynchronous filename generation
It is possible with this library to
diff --git a/docs/scripts/linenumber.js b/docs/scripts/linenumber.js
index 8d52f7e..4354785 100644
--- a/docs/scripts/linenumber.js
+++ b/docs/scripts/linenumber.js
@@ -1,12 +1,12 @@
/*global document */
-(function() {
- var source = document.getElementsByClassName('prettyprint source linenums');
- var i = 0;
- var lineNumber = 0;
- var lineId;
- var lines;
- var totalLines;
- var anchorHash;
+(() => {
+ const source = document.getElementsByClassName('prettyprint source linenums');
+ let i = 0;
+ let lineNumber = 0;
+ let lineId;
+ let lines;
+ let totalLines;
+ let anchorHash;
if (source && source[0]) {
anchorHash = document.location.hash.substring(1);
@@ -15,7 +15,7 @@
for (; i < totalLines; i++) {
lineNumber++;
- lineId = 'line' + lineNumber;
+ lineId = `line${lineNumber}`;
lines[i].id = lineId;
if (lineId === anchorHash) {
lines[i].className += ' selected';
diff --git a/docs/styles/jsdoc-default.css b/docs/styles/jsdoc-default.css
index ede1919..7d1729d 100644
--- a/docs/styles/jsdoc-default.css
+++ b/docs/styles/jsdoc-default.css
@@ -78,6 +78,10 @@ article dl {
margin-bottom: 40px;
}
+article img {
+ max-width: 100%;
+}
+
section
{
display: block;
@@ -218,8 +222,8 @@ thead tr
th { border-right: 1px solid #aaa; }
tr > th:last-child { border-right: 1px solid #ddd; }
-.ancestors { color: #999; }
-.ancestors a
+.ancestors, .attribs { color: #999; }
+.ancestors a, .attribs a
{
color: #999 !important;
text-decoration: none;
@@ -269,7 +273,7 @@ tr > th:last-child { border-right: 1px solid #ddd; }
margin: 0;
}
-.prettyprint
+.source
{
border: 1px solid #ddd;
width: 80%;
@@ -280,7 +284,7 @@ tr > th:last-child { border-right: 1px solid #ddd; }
width: inherit;
}
-.prettyprint code
+.source code
{
font-size: 100%;
line-height: 18px;
diff --git a/docs/tmp.js.html b/docs/tmp.js.html
index 7203f53..1e4eb63 100644
--- a/docs/tmp.js.html
+++ b/docs/tmp.js.html
@@ -29,7 +29,7 @@
* Module dependencies.
*/
const fs = require('fs');
+const os = require('os');
const path = require('path');
const crypto = require('crypto');
-const osTmpDir = require('os-tmpdir');
-const _c = process.binding('constants');
+const _c = { fs: fs.constants, os: os.constants };
/*
* The working inner variables.
*/
const
- /**
- * The temporary directory.
- * @type {string}
- */
- tmpDir = osTmpDir(),
-
// the random characters to choose from
RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
@@ -62,106 +56,44 @@
Source: tmp.js
CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),
+ // constants are off on the windows platform and will not match the actual errno codes
+ IS_WIN32 = os.platform() === 'win32',
EBADF = _c.EBADF || _c.os.errno.EBADF,
ENOENT = _c.ENOENT || _c.os.errno.ENOENT,
- DIR_MODE = 448 /* 0o700 */,
- FILE_MODE = 384 /* 0o600 */,
-
- // this will hold the objects need to be removed on exit
- _removeObjects = [];
-
-var
- _gracefulCleanup = false,
- _uncaughtException = false;
-
-/**
- * Random name generator based on crypto.
- * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
- *
- * @param {number} howMany
- * @returns {string} the generated random name
- * @private
- */
-function _randomChars(howMany) {
- var
- value = [],
- rnd = null;
+ DIR_MODE = 0o700 /* 448 */,
+ FILE_MODE = 0o600 /* 384 */,
- // make sure that we do not fail because we ran out of entropy
- try {
- rnd = crypto.randomBytes(howMany);
- } catch (e) {
- rnd = crypto.pseudoRandomBytes(howMany);
- }
+ EXIT = 'exit',
- for (var i = 0; i < howMany; i++) {
- value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
- }
+ // this will hold the objects need to be removed on exit
+ _removeObjects = [],
- return value.join('');
-}
+ // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback
+ FN_RMDIR_SYNC = fs.rmdirSync.bind(fs);
-/**
- * Checks whether the `obj` parameter is defined or not.
- *
- * @param {Object} obj
- * @returns {boolean} true if the object is undefined
- * @private
- */
-function _isUndefined(obj) {
- return typeof obj === 'undefined';
-}
+let
+ _gracefulCleanup = false;
/**
- * Parses the function arguments.
- *
- * This function helps to have optional arguments.
+ * Recursively remove a directory and its contents.
*
- * @param {(Options|Function)} options
+ * @param {string} dirPath path of directory to remove
* @param {Function} callback
- * @returns {Array} parsed arguments
* @private
*/
-function _parseArguments(options, callback) {
- if (typeof options == 'function') {
- var
- tmp = options,
- options = callback || {},
- callback = tmp;
- } else if (typeof options == 'undefined') {
- options = {};
- }
-
- return [options, callback];
+function rimraf(dirPath, callback) {
+ return fs.rm(dirPath, { recursive: true }, callback);
}
/**
- * Generates a new temporary name.
+ * Recursively remove a directory and its contents, synchronously.
*
- * @param {Object} opts
- * @returns {string} the new random name according to opts
+ * @param {string} dirPath path of directory to remove
* @private
*/
-function _generateTmpName(opts) {
- if (opts.name) {
- return path.join(opts.dir || tmpDir, opts.name);
- }
-
- // mkstemps like template
- if (opts.template) {
- return opts.template.replace(TEMPLATE_PATTERN, _randomChars(6));
- }
-
- // prefix and postfix
- const name = [
- opts.prefix || 'tmp-',
- process.pid,
- _randomChars(12),
- opts.postfix || ''
- ].join('');
-
- return path.join(opts.dir || tmpDir, name);
+function FN_RIMRAF_SYNC(dirPath) {
+ return fs.rmSync(dirPath, { recursive: true });
}
/**
@@ -171,31 +103,37 @@
Source: tmp.js
* @param {?tmpNameCallback} callback the callback function
*/
function tmpName(options, callback) {
- var
+ const
args = _parseArguments(options, callback),
opts = args[0],
- cb = args[1],
- tries = opts.tries || DEFAULT_TRIES;
-
- if (isNaN(tries) || tries < 0)
- return cb(new Error('Invalid tries'));
+ cb = args[1];
- if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
- return cb(new Error('Invalid template provided'));
+ try {
+ _assertAndSanitizeOptions(opts);
+ } catch (err) {
+ return cb(err);
+ }
+ let tries = opts.tries;
(function _getUniqueName() {
- const name = _generateTmpName(opts);
+ try {
+ const name = _generateTmpName(opts);
- // check whether the path exists then retry if needed
- fs.stat(name, function (err) {
- if (!err) {
- if (tries-- > 0) return _getUniqueName();
+ // check whether the path exists then retry if needed
+ fs.stat(name, function (err) {
+ /* istanbul ignore else */
+ if (!err) {
+ /* istanbul ignore else */
+ if (tries-- > 0) return _getUniqueName();
- return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
- }
+ return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
+ }
- cb(null, name);
- });
+ cb(null, name);
+ });
+ } catch (err) {
+ cb(err);
+ }
}());
}
@@ -207,17 +145,13 @@
Source: tmp.js
* @throws {Error} if the options are invalid or could not generate a filename
*/
function tmpNameSync(options) {
- var
+ const
args = _parseArguments(options),
- opts = args[0],
- tries = opts.tries || DEFAULT_TRIES;
-
- if (isNaN(tries) || tries < 0)
- throw new Error('Invalid tries');
+ opts = args[0];
- if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
- throw new Error('Invalid template provided');
+ _assertAndSanitizeOptions(opts);
+ let tries = opts.tries;
do {
const name = _generateTmpName(opts);
try {
@@ -233,46 +167,36 @@
Source: tmp.js
/**
* Creates and opens a temporary file.
*
- * @param {(Options|fileCallback)} options the config options or the callback function
+ * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined
* @param {?fileCallback} callback
*/
function file(options, callback) {
- var
+ const
args = _parseArguments(options, callback),
opts = args[0],
cb = args[1];
- opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix;
-
// gets a temporary filename
tmpName(opts, function _tmpNameCreated(err, name) {
+ /* istanbul ignore else */
if (err) return cb(err);
// create and open the file
fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {
+ /* istanbu ignore else */
if (err) return cb(err);
if (opts.discardDescriptor) {
- return fs.close(fd, function _discardCallback(err) {
- if (err) {
- // Low probability, and the file exists, so this could be
- // ignored. If it isn't we certainly need to unlink the
- // file, and if that fails too its error is more
- // important.
- try {
- fs.unlinkSync(name);
- } catch (e) {
- err = e;
- }
- return cb(err);
- }
- cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts));
+ return fs.close(fd, function _discardCallback(possibleErr) {
+ // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only
+ return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false));
});
+ } else {
+ // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care
+ // about the descriptor
+ const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
+ cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));
}
- if (opts.detachDescriptor) {
- return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts));
- }
- cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts));
});
});
}
@@ -285,59 +209,26 @@
Source: tmp.js
* @throws {Error} if cannot create a file
*/
function fileSync(options) {
- var
+ const
args = _parseArguments(options),
opts = args[0];
- opts.postfix = opts.postfix || '.tmp';
-
+ const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
const name = tmpNameSync(opts);
- const fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
+ var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
+ /* istanbul ignore else */
+ if (opts.discardDescriptor) {
+ fs.closeSync(fd);
+ fd = undefined;
+ }
return {
name: name,
fd: fd,
- removeCallback: _prepareTmpFileRemoveCallback(name, fd, opts)
+ removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)
};
}
-/**
- * Removes files and folders in a directory recursively.
- *
- * @param {string} root
- * @private
- */
-function _rmdirRecursiveSync(root) {
- const dirs = [root];
-
- do {
- var
- dir = dirs.pop(),
- deferred = false,
- files = fs.readdirSync(dir);
-
- for (var i = 0, length = files.length; i < length; i++) {
- var
- file = path.join(dir, files[i]),
- stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories
-
- if (stat.isDirectory()) {
- if (!deferred) {
- deferred = true;
- dirs.push(dir);
- }
- dirs.push(file);
- } else {
- fs.unlinkSync(file);
- }
- }
-
- if (!deferred) {
- fs.rmdirSync(dir);
- }
- } while (dirs.length !== 0);
-}
-
/**
* Creates a temporary directory.
*
@@ -345,20 +236,22 @@
Source: tmp.js
* @param {?dirCallback} callback
*/
function dir(options, callback) {
- var
+ const
args = _parseArguments(options, callback),
opts = args[0],
cb = args[1];
// gets a temporary filename
tmpName(opts, function _tmpNameCreated(err, name) {
+ /* istanbul ignore else */
if (err) return cb(err);
// create the directory
fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
+ /* istanbul ignore else */
if (err) return cb(err);
- cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
+ cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));
});
});
}
@@ -371,7 +264,7 @@
Source: tmp.js
* @throws {Error} if it cannot create a directory
*/
function dirSync(options) {
- var
+ const
args = _parseArguments(options),
opts = args[0];
@@ -380,87 +273,138 @@
Source: tmp.js
return {
name: name,
- removeCallback: _prepareTmpDirRemoveCallback(name, opts)
+ removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)
};
}
/**
- * Prepares the callback for removal of the temporary file.
+ * Removes files asynchronously.
*
- * @param {string} name the path of the file
- * @param {number} fd file descriptor
- * @param {Object} opts
- * @returns {fileCallback}
+ * @param {Object} fdPath
+ * @param {Function} next
+ * @private
+ */
+function _removeFileAsync(fdPath, next) {
+ const _handler = function (err) {
+ if (err && !_isENOENT(err)) {
+ // reraise any unanticipated error
+ return next(err);
+ }
+ next();
+ };
+
+ if (0 <= fdPath[0])
+ fs.close(fdPath[0], function () {
+ fs.unlink(fdPath[1], _handler);
+ });
+ else fs.unlink(fdPath[1], _handler);
+}
+
+/**
+ * Removes files synchronously.
+ *
+ * @param {Object} fdPath
* @private
*/
-function _prepareTmpFileRemoveCallback(name, fd, opts) {
- const removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
+function _removeFileSync(fdPath) {
+ let rethrownException = null;
+ try {
+ if (0 <= fdPath[0]) fs.closeSync(fdPath[0]);
+ } catch (e) {
+ // reraise any unanticipated error
+ if (!_isEBADF(e) && !_isENOENT(e)) throw e;
+ } finally {
try {
- if (0 <= fdPath[0]) {
- fs.closeSync(fdPath[0]);
- }
+ fs.unlinkSync(fdPath[1]);
}
catch (e) {
- // under some node/windows related circumstances, a temporary file
- // may have not be created as expected or the file was already closed
- // by the user, in which case we will simply ignore the error
- if (e.errno != -EBADF && e.errno != -ENOENT) {
- // reraise any unanticipated error
- throw e;
- }
+ // reraise any unanticipated error
+ if (!_isENOENT(e)) rethrownException = e;
}
- fs.unlinkSync(fdPath[1]);
- }, [fd, name]);
-
- if (!opts.keep) {
- _removeObjects.unshift(removeCallback);
}
+ if (rethrownException !== null) {
+ throw rethrownException;
+ }
+}
+
+/**
+ * Prepares the callback for removal of the temporary file.
+ *
+ * Returns either a sync callback or a async callback depending on whether
+ * fileSync or file was called, which is expressed by the sync parameter.
+ *
+ * @param {string} name the path of the file
+ * @param {number} fd file descriptor
+ * @param {Object} opts
+ * @param {boolean} sync
+ * @returns {fileCallback | fileCallbackSync}
+ * @private
+ */
+function _prepareTmpFileRemoveCallback(name, fd, opts, sync) {
+ const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);
+ const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);
- return removeCallback;
+ if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
+
+ return sync ? removeCallbackSync : removeCallback;
}
/**
* Prepares the callback for removal of the temporary directory.
*
+ * Returns either a sync callback or a async callback depending on whether
+ * tmpFileSync or tmpFile was called, which is expressed by the sync parameter.
+ *
* @param {string} name
* @param {Object} opts
+ * @param {boolean} sync
* @returns {Function} the callback
* @private
*/
-function _prepareTmpDirRemoveCallback(name, opts) {
- const removeFunction = opts.unsafeCleanup ? _rmdirRecursiveSync : fs.rmdirSync.bind(fs);
- const removeCallback = _prepareRemoveCallback(removeFunction, name);
-
- if (!opts.keep) {
- _removeObjects.unshift(removeCallback);
- }
-
- return removeCallback;
+function _prepareTmpDirRemoveCallback(name, opts, sync) {
+ const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs);
+ const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;
+ const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);
+ const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);
+ if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
+
+ return sync ? removeCallbackSync : removeCallback;
}
/**
* Creates a guarded function wrapping the removeFunction call.
*
+ * The cleanup callback is save to be called multiple times.
+ * Subsequent invocations will be ignored.
+ *
* @param {Function} removeFunction
- * @param {Object} arg
- * @returns {Function}
+ * @param {string} fileOrDirName
+ * @param {boolean} sync
+ * @param {cleanupCallbackSync?} cleanupCallbackSync
+ * @returns {cleanupCallback | cleanupCallbackSync}
* @private
*/
-function _prepareRemoveCallback(removeFunction, arg) {
- var called = false;
+function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {
+ let called = false;
+ // if sync is true, the next parameter will be ignored
return function _cleanupCallback(next) {
+
+ /* istanbul ignore else */
if (!called) {
- const index = _removeObjects.indexOf(_cleanupCallback);
- if (index >= 0) {
- _removeObjects.splice(index, 1);
- }
+ // remove cleanupCallback from cache
+ const toRemove = cleanupCallbackSync || _cleanupCallback;
+ const index = _removeObjects.indexOf(toRemove);
+ /* istanbul ignore else */
+ if (index >= 0) _removeObjects.splice(index, 1);
called = true;
- removeFunction(arg);
+ if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {
+ return removeFunction(fileOrDirName);
+ } else {
+ return removeFunction(fileOrDirName, next || function() {});
+ }
}
-
- if (next) next(null);
};
}
@@ -470,64 +414,315 @@
Source: tmp.js
* @private
*/
function _garbageCollector() {
- if (_uncaughtException && !_gracefulCleanup) {
- return;
- }
+ /* istanbul ignore else */
+ if (!_gracefulCleanup) return;
// the function being called removes itself from _removeObjects,
// loop until _removeObjects is empty
while (_removeObjects.length) {
try {
- _removeObjects[0].call(null);
+ _removeObjects[0]();
} catch (e) {
// already removed?
}
}
}
+/**
+ * Random name generator based on crypto.
+ * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
+ *
+ * @param {number} howMany
+ * @returns {string} the generated random name
+ * @private
+ */
+function _randomChars(howMany) {
+ let
+ value = [],
+ rnd = null;
+
+ // make sure that we do not fail because we ran out of entropy
+ try {
+ rnd = crypto.randomBytes(howMany);
+ } catch (e) {
+ rnd = crypto.pseudoRandomBytes(howMany);
+ }
+
+ for (var i = 0; i < howMany; i++) {
+ value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
+ }
+
+ return value.join('');
+}
+
+/**
+ * Helper which determines whether a string s is blank, that is undefined, or empty or null.
+ *
+ * @private
+ * @param {string} s
+ * @returns {Boolean} true whether the string s is blank, false otherwise
+ */
+function _isBlank(s) {
+ return s === null || _isUndefined(s) || !s.trim();
+}
+
+/**
+ * Checks whether the `obj` parameter is defined or not.
+ *
+ * @param {Object} obj
+ * @returns {boolean} true if the object is undefined
+ * @private
+ */
+function _isUndefined(obj) {
+ return typeof obj === 'undefined';
+}
+
+/**
+ * Parses the function arguments.
+ *
+ * This function helps to have optional arguments.
+ *
+ * @param {(Options|null|undefined|Function)} options
+ * @param {?Function} callback
+ * @returns {Array} parsed arguments
+ * @private
+ */
+function _parseArguments(options, callback) {
+ /* istanbul ignore else */
+ if (typeof options === 'function') {
+ return [{}, options];
+ }
+
+ /* istanbul ignore else */
+ if (_isUndefined(options)) {
+ return [{}, callback];
+ }
+
+ // copy options so we do not leak the changes we make internally
+ const actualOptions = {};
+ for (const key of Object.getOwnPropertyNames(options)) {
+ actualOptions[key] = options[key];
+ }
+
+ return [actualOptions, callback];
+}
+
+/**
+ * Generates a new temporary name.
+ *
+ * @param {Object} opts
+ * @returns {string} the new random name according to opts
+ * @private
+ */
+function _generateTmpName(opts) {
+
+ const tmpDir = opts.tmpdir;
+
+ /* istanbul ignore else */
+ if (!_isUndefined(opts.name))
+ return path.join(tmpDir, opts.dir, opts.name);
+
+ /* istanbul ignore else */
+ if (!_isUndefined(opts.template))
+ return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));
+
+ // prefix and postfix
+ const name = [
+ opts.prefix ? opts.prefix : 'tmp',
+ '-',
+ process.pid,
+ '-',
+ _randomChars(12),
+ opts.postfix ? '-' + opts.postfix : ''
+ ].join('');
+
+ return path.join(tmpDir, opts.dir, name);
+}
+
+/**
+ * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing
+ * options.
+ *
+ * @param {Options} options
+ * @private
+ */
+function _assertAndSanitizeOptions(options) {
+
+ options.tmpdir = _getTmpDir(options);
+
+ const tmpDir = options.tmpdir;
+
+ /* istanbul ignore else */
+ if (!_isUndefined(options.name))
+ _assertIsRelative(options.name, 'name', tmpDir);
+ /* istanbul ignore else */
+ if (!_isUndefined(options.dir))
+ _assertIsRelative(options.dir, 'dir', tmpDir);
+ /* istanbul ignore else */
+ if (!_isUndefined(options.template)) {
+ _assertIsRelative(options.template, 'template', tmpDir);
+ if (!options.template.match(TEMPLATE_PATTERN))
+ throw new Error(`Invalid template, found "${options.template}".`);
+ }
+ /* istanbul ignore else */
+ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0)
+ throw new Error(`Invalid tries, found "${options.tries}".`);
+
+ // if a name was specified we will try once
+ options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;
+ options.keep = !!options.keep;
+ options.detachDescriptor = !!options.detachDescriptor;
+ options.discardDescriptor = !!options.discardDescriptor;
+ options.unsafeCleanup = !!options.unsafeCleanup;
+
+ // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to
+ options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir));
+ options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir));
+ // sanitize further if template is relative to options.dir
+ options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template);
+
+ // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to
+ options.name = _isUndefined(options.name) ? undefined : options.name;
+ options.prefix = _isUndefined(options.prefix) ? '' : options.prefix;
+ options.postfix = _isUndefined(options.postfix) ? '' : options.postfix;
+}
+
+/**
+ * Resolve the specified path name in respect to tmpDir.
+ *
+ * The specified name might include relative path components, e.g. ../
+ * so we need to resolve in order to be sure that is is located inside tmpDir
+ *
+ * @param name
+ * @param tmpDir
+ * @returns {string}
+ * @private
+ */
+function _resolvePath(name, tmpDir) {
+ if (name.startsWith(tmpDir)) {
+ return path.resolve(name);
+ } else {
+ return path.resolve(path.join(tmpDir, name));
+ }
+}
+
+/**
+ * Asserts whether specified name is relative to the specified tmpDir.
+ *
+ * @param {string} name
+ * @param {string} option
+ * @param {string} tmpDir
+ * @throws {Error}
+ * @private
+ */
+function _assertIsRelative(name, option, tmpDir) {
+ if (option === 'name') {
+ // assert that name is not absolute and does not contain a path
+ if (path.isAbsolute(name))
+ throw new Error(`${option} option must not contain an absolute path, found "${name}".`);
+ // must not fail on valid .<name> or ..<name> or similar such constructs
+ let basename = path.basename(name);
+ if (basename === '..' || basename === '.' || basename !== name)
+ throw new Error(`${option} option must not contain a path, found "${name}".`);
+ }
+ else { // if (option === 'dir' || option === 'template') {
+ // assert that dir or template are relative to tmpDir
+ if (path.isAbsolute(name) && !name.startsWith(tmpDir)) {
+ throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`);
+ }
+ let resolvedPath = _resolvePath(name, tmpDir);
+ if (!resolvedPath.startsWith(tmpDir))
+ throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`);
+ }
+}
+
+/**
+ * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.
+ *
+ * @private
+ */
+function _isEBADF(error) {
+ return _isExpectedError(error, -EBADF, 'EBADF');
+}
+
+/**
+ * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.
+ *
+ * @private
+ */
+function _isENOENT(error) {
+ return _isExpectedError(error, -ENOENT, 'ENOENT');
+}
+
+/**
+ * Helper to determine whether the expected error code matches the actual code and errno,
+ * which will differ between the supported node versions.
+ *
+ * - Node >= 7.0:
+ * error.code {string}
+ * error.errno {number} any numerical value will be negated
+ *
+ * CAVEAT
+ *
+ * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT
+ * is no different here.
+ *
+ * @param {SystemError} error
+ * @param {number} errno
+ * @param {string} code
+ * @private
+ */
+function _isExpectedError(error, errno, code) {
+ return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno;
+}
+
/**
* Sets the graceful cleanup.
*
- * Also removes the created files and directories when an uncaught exception occurs.
+ * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the
+ * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary
+ * object removals.
*/
function setGracefulCleanup() {
_gracefulCleanup = true;
}
-const version = process.versions.node.split('.').map(function (value) {
- return parseInt(value, 10);
-});
-
-if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
- process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
- _uncaughtException = true;
- _garbageCollector();
-
- throw err;
- });
+/**
+ * Returns the currently configured tmp dir from os.tmpdir().
+ *
+ * @private
+ * @param {?Options} options
+ * @returns {string} the currently configured tmp dir
+ */
+function _getTmpDir(options) {
+ return path.resolve(options && options.tmpdir || os.tmpdir());
}
-process.addListener('exit', function _exit(code) {
- if (code) _uncaughtException = true;
- _garbageCollector();
-});
+// Install process exit listener
+process.addListener(EXIT, _garbageCollector);
/**
* Configuration options.
*
* @typedef {Object} Options
+ * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected
* @property {?number} tries the number of tries before give up the name generation
+ * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files
* @property {?string} template the "mkstemp" like filename template
- * @property {?string} name fix name
- * @property {?string} dir the tmp directory to use
+ * @property {?string} name fixed name relative to tmpdir or the specified dir option
+ * @property {?string} dir tmp directory relative to the root tmp directory in use
* @property {?string} prefix prefix for the generated name
* @property {?string} postfix postfix for the generated name
+ * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir
+ * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty
+ * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection
+ * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection
*/
/**
* @typedef {Object} FileSyncObject
* @property {string} name the name of the file
- * @property {string} fd the file descriptor
+ * @property {string} fd the file descriptor or -1 if the fd has been discarded
* @property {fileCallback} removeCallback the callback function to remove the file
*/
@@ -547,10 +742,18 @@
Source: tmp.js
* @callback fileCallback
* @param {?Error} err the error object if anything goes wrong
* @param {string} name the temporary file name
- * @param {number} fd the file descriptor
+ * @param {number} fd the file descriptor or -1 if the fd had been discarded
* @param {cleanupCallback} fn the cleanup callback function
*/
+/**
+ * @callback fileCallbackSync
+ * @param {?Error} err the error object if anything goes wrong
+ * @param {string} name the temporary file name
+ * @param {number} fd the file descriptor or -1 if the fd had been discarded
+ * @param {cleanupCallbackSync} fn the cleanup callback function
+ */
+
/**
* @callback dirCallback
* @param {?Error} err the error object if anything goes wrong
@@ -558,11 +761,24 @@
Source: tmp.js
* @param {cleanupCallback} fn the cleanup callback function
*/
+/**
+ * @callback dirCallbackSync
+ * @param {?Error} err the error object if anything goes wrong
+ * @param {string} name the temporary file name
+ * @param {cleanupCallbackSync} fn the cleanup callback function
+ */
+
/**
* Removes the temporary created file or directory.
*
* @callback cleanupCallback
- * @param {simpleCallback} [next] function to call after entry was removed
+ * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed
+ */
+
+/**
+ * Removes the temporary created file or directory.
+ *
+ * @callback cleanupCallbackSync
*/
/**
@@ -573,7 +789,16 @@
Source: tmp.js
*/
// exporting all the needed methods
-module.exports.tmpdir = tmpDir;
+
+// evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will
+// allow users to reconfigure the temporary directory
+Object.defineProperty(module.exports, 'tmpdir', {
+ enumerable: true,
+ configurable: false,
+ get: function () {
+ return _getTmpDir();
+ }
+});
module.exports.dir = dir;
module.exports.dirSync = dirSync;
@@ -595,13 +820,13 @@