@nfi/safeish-tmp
TypeScript icon, indicating that this package has built-in type declarations

2.1.1 • Public • Published

@nfi/safeish-tmp

npm version pipeline status coverage status standard-js

Simplified creation, scrubbing and deletion of temporary files.

Installation

npm install @nfi/safeish-tmp

Documentation

API documentation is available here.

Example

Standard form, using open/openSync:

const safeish = require('@nfi/safeish-tmp')
const child = require('child_process')
const util = require('util')
const execP = util.promisify(child.exec)

async function wrapperFunction(inData) {
  // create two temp files with randomised paths
  const inFile = await safeish.open()
  const outFile = await safeish.open()
  try {
    // prepare one file with input data
    await inFile.write(inData)
    // pass file paths to poorly built command-line utility that
    // didn't allow you to do what you needed using stdin/stdout
    await execP('/usr/bin/im_the_reason_this_package_exists', [
      '--input', inFile.path,
      '--output', outFile.path
    ])
    // retrieve output data from the second file
    return await outFile.readAll()
  } finally {
    // close, scrub and delete both files when finished
    await inFile.close()
    await outFile.close()
  }
}

Alternative form, using guard/guardSync:

const safeish = require('@nfi/safeish-tmp')
const child = require('child_process')
const util = require('util')
const execP = util.promisify(child.exec)

async function wrapperFunction(inData) {
  // create two temp files with randomised paths
  return safeish.guard(async (inFile) => {
    return safeish.guard(async (outFile) => {
      // prepare one file with input data
      await inFile.write(inData)
      // pass file paths to poorly built command-line utility that
      // didn't allow you to do what you needed using stdin/stdout
      await execP('/usr/bin/im_the_reason_this_package_exists', [
        '--input', inFile.path,
        '--output', outFile.path
      ])
      // retrieve output data from the second file; this value will
      // be passed back through the calls to guard()
      return await outFile.readAll()
    })
  })
  // both files are automatically closed, scrubbed and deleted
  // once the callback (or its returned promise) completes
}

Catch-all cleanup on exit:

const safeish = require('@nfi/safeish-tmp')

// close, scrub and delete any remaining open files
process.on('exit', safeish.closeAllSync)

Package Sidebar

Install

npm i @nfi/safeish-tmp

Weekly Downloads

5

Version

2.1.1

License

ISC

Unpacked Size

29.3 kB

Total Files

10

Last publish

Collaborators

  • cptpackrat