• Stars
    star
    437
  • Rank 99,659 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 14 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Temporary File, Directory, and Stream support for Node.js

Image of node-temp logo

Temporary files, directories, and streams for Node.js.

Handles generating a unique file/directory name under the appropriate system temporary directory, changing the file to an appropriate mode, and supports automatic removal (if asked)

temp has a similar API to the fs module.

Node.js Compatibility

Supports v6.0.0+.

Build Status

Please let me know if you have problems running it on a later version of Node.js or have platform-specific problems.

Installation

Install it using npm:

$ npm install temp

Or get it directly from: http://github.com/bruce/node-temp

Synopsis

You can create temporary files with open and openSync, temporary directories with mkdir and mkdirSync, or you can get a unique name in the system temporary directory with path.

See the API section for more details on the API of temp.

Working copies of the following examples can be found under the examples directory.

Temporary Files (open and openSync)

To create a temporary file use open or openSync, passing them an optional prefix, suffix, or both (see below for details on affixes). The object passed to the callback (or returned) has path and fd keys:

{ path: "/path/to/file",
, fd: theFileDescriptor
}

In this example we write to a temporary file and call out to grep and wc -l to determine the number of time foo occurs in the text. The temporary file is chmod'd 0600 and cleaned up automatically when the process at exit (because temp.track() is called):

var temp = require('temp'),
    fs   = require('fs'),
    util  = require('util'),
    exec = require('child_process').exec;

// Automatically track and cleanup files at exit
temp.track();

// Fake data
var myData = "foo\nbar\nfoo\nbaz";

// Process the data (note: error handling omitted)
temp.open('myprefix', function(err, info) {
  if (!err) {
    fs.write(info.fd, myData, (err) => {
		console.log(err);
	});
    fs.close(info.fd, function(err) {
      exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
        util.puts(stdout.trim());
      });
    });
  }
});

Want Cleanup? Make sure you ask for it. (track)

As noted in the example above, if you want temp to track the files and directories it creates and handle removing those files and directories on exit, you must call track(). The track() function is chainable, and it's recommended that you call it when requiring the module.

var temp = require("temp").track();

Why is this necessary? In pre-0.6 versions of temp, tracking was automatic. While this works great for scripts and Grunt tasks, it's not so great for long-running server processes. Since that's arguably what Node.js is for, you have to opt-in to tracking.

But it's easy.

Cleanup anytime (cleanup, cleanupSync)

When tracking, you can run cleanup() and cleanupSync() anytime (cleanupSync() will be run for you on process exit). An object will be returned (or passed to the callback) with cleanup counts and the file/directory tracking lists will be reset.

> temp.cleanupSync();
{ files: 1,
  dirs:  0 }
> temp.cleanup(function(err, stats) {
    console.log(stats);
  });
{ files: 1,
  dirs:  0 }

Note: If you're not tracking, an error ("not tracking") will be passed to the callback.

Temporary Directories (mkdir, mkdirSync)

To create a temporary directory, use mkdir or mkdirSync, passing it an optional prefix, suffix, or both (see below for details on affixes).

In this example we create a temporary directory, write to a file within it, call out to an external program to create a PDF, and read the result. While the external process creates a lot of additional files, the temporary directory is removed automatically at exit (because temp.track() is called):

var temp = require('temp'),
    fs   = require('fs'),
    util = require('util'),
    path = require('path'),
    exec = require('child_process').exec;

// Automatically track and cleanup files at exit
temp.track();

// For use with ConTeXt, http://wiki.contextgarden.net
var myData = "\\starttext\nHello World\n\\stoptext";

temp.mkdir('pdfcreator', function(err, dirPath) {
  var inputPath = path.join(dirPath, 'input.tex')
  fs.writeFile(inputPath, myData, function(err) {
    if (err) throw err;
    process.chdir(dirPath);
    exec("texexec '" + inputPath + "'", function(err) {
      if (err) throw err;
      fs.readFile(path.join(dirPath, 'input.pdf'), function(err, data) {
        if (err) throw err;
        sys.print(data);
      });
    });
  });
});

Temporary Streams (createWriteStream)

To create a temporary WriteStream, use 'createWriteStream', which sits on top of fs.createWriteStream. The return value is a fs.WriteStream with a path property containing the temporary file path for the stream. The path is registered for removal when temp.cleanup is called (because temp.track() is called).

var temp = require('temp');

// Automatically track and cleanup files at exit
temp.track();

var stream = temp.createWriteStream();
// stream.path contains the temporary file path for the stream
stream.write("Some data");
// Maybe do some other things
stream.end();

Affixes (options)

You can provide custom prefixes and suffixes when creating temporary files and directories. If you provide a string, it is used as the prefix for the temporary name. If you provide an object with prefix, suffix and dir keys, they are used for the temporary name.

Here are some examples:

  • "aprefix": A simple prefix, prepended to the filename; this is shorthand for:
  • {prefix: "aprefix"}: A simple prefix, prepended to the filename
  • {suffix: ".asuffix"}: A suffix, appended to the filename (especially useful when the file needs to be named with specific extension for use with an external program).
  • {prefix: "myprefix", suffix: "mysuffix"}: Customize both affixes
  • {dir: path.join(os.tmpdir(), "myapp")}: default prefix and suffix within a new temporary directory.
  • null: Use the defaults for files and directories (prefixes "f-" and "d-", respectively, no suffixes).

In this simple example we read a pdf, write it to a temporary file with a .pdf extension, and close it.

var fs   = require('fs'),
    temp = require('temp');

fs.readFile('/path/to/source.pdf', function(err, data) {
  temp.open({suffix: '.pdf'}, function(err, info) {
    if (err) throw err;
    fs.write(info.fd, data, (err) => {
			console.log(err)
		});
    fs.close(info.fd, function(err) {
      if (err) throw err;
      // Do something with the file
    });
  });
});

Just a path, please (path)

If you just want a unique name in your temporary directory, use path:

var fs = require('fs');
var tempName = temp.path({suffix: '.pdf'});
// Do something with tempName

Note: The file isn't created for you, and the mode is not changed -- and it will not be removed automatically at exit. If you use path, it's all up to you.

API

interface OpenFile {
	path: string;
	fd: number;
}

interface Stats {
	files: number;
	dirs: number;
}

interface AffixOptions {
	prefix?: string;
	suffix?: string;
	dir?: string;
}

function track(value?: boolean): typeof temp;

function mkdir(affixes: string | AffixOptions | undefined, callback: (err: any, dirPath: string) => void): void;
function mkdir(affixes?: string | AffixOptions): Promise<string>;

function mkdirSync(affixes?: string | AffixOptions): string;

function open(affixes: string | AffixOptions | undefined, callback: (err: any, result: OpenFile) => void): void;
function open(affixes?: string | AffixOptions): Promise<OpenFile>;

function openSync(affixes?: string | AffixOptions): OpenFile;

function path(affixes?: string | AffixOptions, defaultPrefix?: string): string;

function cleanup(callback: (err: any, result: Stats) => void): void;
function cleanup(): Promise<Stats>;

function cleanupSync(): boolean | Stats;

function createWriteStream(affixes?: string | AffixOptions): fs.WriteStream;

Testing

$ npm test

Contributing

You can find the repository at: http://github.com/bruce/node-temp

Issues/Feature Requests can be submitted at: http://github.com/bruce/node-temp/issues

I'd really like to hear your feedback, and I'd love to receive your pull-requests!

Copyright

Copyright (c) 2010-2014 Bruce Williams. This software is licensed under the MIT License, see LICENSE for details.

More Repositories

1

keyword_search

Generic support for extracting GMail-style search keywords/values from strings
Ruby
100
star
2

emacs-spacegray-theme

A Hyperminimal UI Theme for Emacs
Emacs Lisp
58
star
3

rtex

No longer maintained (free to a good home!)
Ruby
57
star
4

graphy

Graph Theory library for Ruby
Ruby
48
star
5

bumpspark

Generates bumpspark-style sparklines as PNG (including Data URI support) from Ruby and Rails.
Ruby
41
star
6

bitmask-attribute

Official repo is now: https://github.com/joelmoss/bitmask_attributes
Ruby
34
star
7

goose

A flexible, simple Rails plugin that simplifies navigation and breadcrumbs..
Ruby
28
star
8

linguistics

Michael Granger's Linguistics framework for Ruby (from SVN)
Ruby
28
star
9

ie_conditional_tag

Provides an easy-to-use helper for generating multiple tags inside IE-specific conditional comments
Ruby
24
star
10

atom-csscomb

Atom Editor Plugin for CSSComb [NOT MAINTAINED, SEE ISSUES]
CoffeeScript
22
star
11

paginator

Generic pagination support for Ruby
Ruby
21
star
12

puppet-vcsrepo

See the official repo: https://github.com/puppetlabs/puppet-vcsrepo
Ruby
19
star
13

jsonpath

No longer maintained; see https://github.com/joshbuddy/jsonpath
Ruby
18
star
14

tinge

Extract color information from CSS/SCSS files (for various formats)
Ruby
16
star
15

esi

Eve Online Swagger Interface (ESI) for Elixir
Elixir
15
star
16

twfy

Ruby binding for TheyWorkForYou.com API (keep tabs on representatives in Parliament and other assemblies)
Ruby
12
star
17

deploydemo

A simple example showing multi-branch, multi-stage deployments using Actions
Shell
11
star
18

spex

Test harness for executables
Ruby
11
star
19

pastex

ElixirConf 2018 GraphQL Training
Elixir
10
star
20

shorthand

Build simple configuration DSLs on top of existing attribute writers with a simple module inclusion
Ruby
6
star
21

stencil

View delegate plugin for Rails
Ruby
5
star
22

tailnudge

Display OSX notifications based on pattern matches in tailed files
Ruby
5
star
23

rocksteady

Test related/dependent code across different git repos/revisions
Ruby
4
star
24

phoenix-devcontainer-example

An example VSCode devcontainer configuration for an Elixir/Phoenix project
Elixir
4
star
25

compare-app

Ruby 1.8/1.9 Comparison app
Ruby
3
star
26

archibald

Sinatra app to interactively merge family trees (GEDCOM)
3
star
27

lacquer

Decoupled, versioned Ruby DSLs
Ruby
3
star
28

huescene

Define and orchestrate Philips Hue lighting scenes from the commandline
Go
3
star
29

nixos-config

My NixOS configuration
Nix
2
star
30

delve

A simple [experimental] API to access additional information on Ruby 1.9+ objects and methods.
Ruby
2
star
31

dash-haskell

Provides an API for Haskell applications to the FiveRuns Dash service, http://dash.fiveruns.com
Haskell
2
star
32

advent_of_code_elixir

My Elixir solutions for Advent of Code
Elixir
2
star
33

ex_unit_emacs

ExUnit + Emacs Integration
Elixir
1
star
34

clojure-experiments

Bruce's Clojure experiments
Shell
1
star
35

marcotte_grid_demo

Demo of Lynn Wallenstein's marcotte_grid
Ruby
1
star
36

minecraft_tools

Personal tools for managing a Minecraft server
Makefile
1
star
37

puppet-boot

Bootloader support
Ruby
1
star
38

ueberauth_eveonline

Ueberauth EveOnline
Elixir
1
star
39

absinthe-battleship-assets

Assets for an example
HTML
1
star
40

calculator_events

Mentoring example: Calculator with events
Elixir
1
star
41

erlison

A simple single-purpose Usenet client that takes NZBs and downloads files.
Erlang
1
star