pax_global_header00006660000000000000000000000064123700205720014510gustar00rootroot0000000000000052 comment=638084b8d10c08a5392f50c23a42b1401460f873 node-temp-0.8.1/000077500000000000000000000000001237002057200134065ustar00rootroot00000000000000node-temp-0.8.1/.gitignore000066400000000000000000000001021237002057200153670ustar00rootroot00000000000000.DS_Store .\#* /node_modules \#* npm-debug.log node_modules *.tgz node-temp-0.8.1/.travis.yml000066400000000000000000000000601237002057200155130ustar00rootroot00000000000000language: node_js node_js: - "0.11" - "0.10"node-temp-0.8.1/LICENSE000066400000000000000000000020761237002057200144200ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2010-2014 Bruce Williams Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-temp-0.8.1/README.md000066400000000000000000000177101237002057200146730ustar00rootroot00000000000000node-temp ========= 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 v0.10.0+. [![Build Status](https://travis-ci.org/bruce/node-temp.png)](https://travis-ci.org/bruce/node-temp) 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](http://github.com/isaacs/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`. Working copies of the following examples can be found under the `examples` directory. ### Temporary Files 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: ```javascript { 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): ```javascript 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); 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. 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. ```javascript 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](http://gruntjs.com/), 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 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. ```javascript > temp.cleanupSync(); { files: 1, dirs: 0 } ``` ```javascript > 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 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): ```javascript 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 To create a temporary WriteStream, use 'createWriteStream', which sits on top of `fs.createWriteStream`. The return value is a `fs.WriteStream` whose `path` is registered for removal when `temp.cleanup` is called (because `temp.track()` is called). ```javascript var temp = require('temp'); // Automatically track and cleanup files at exit temp.track(); var stream = temp.createWriteStream(); stream.write("Some data"); // Maybe do some other things stream.end(); ``` ### Affixes 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. ```javascript 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, contents); fs.close(info.fd, function(err) { if (err) throw err; // Do something with the file }); }); }); ``` ### Just a path, please If you just want a unique name in your temporary directory, use `path`: ```javascript 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. Using it with Grunt ------------------- If you want to use the module with [Grunt](http://gruntjs.com/), make sure you use `async()` in your Gruntfile: ```javascript module.exports = function (grunt) { var temp = require("temp"); temp.track(); // Cleanup files, please grunt.registerTast("temptest", "Testing temp", function() { var done = this.async(); // Don't forget this! grunt.log.writeln("About to write a file..."); temp.open('tempfile', function(err, info) { // File writing shenanigans here grunt.log.writeln("Wrote a file!") done(); // REALLY don't forget this! }); }); }; ``` For more information, see the [Grunt FAQ](http://gruntjs.com/frequently-asked-questions#why-doesn-t-my-asynchronous-task-complete). Testing ------- ```sh $ 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. node-temp-0.8.1/examples/000077500000000000000000000000001237002057200152245ustar00rootroot00000000000000node-temp-0.8.1/examples/grepcount.js000066400000000000000000000007301237002057200175700ustar00rootroot00000000000000var temp = require('../lib/temp'), fs = require('fs'), util = require('util'), exec = require('child_process').exec; var myData = "foo\nbar\nfoo\nbaz"; temp.open('myprefix', function(err, info) { if (err) throw err; fs.write(info.fd, myData); fs.close(info.fd, function(err) { if (err) throw err; exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) { if (err) throw err; util.puts(stdout.trim()); }); }); }); node-temp-0.8.1/examples/pdfcreator.js000066400000000000000000000012151237002057200177120ustar00rootroot00000000000000var temp = require('../lib/temp'), fs = require('fs'), util = require('util'), path = require('path'), exec = require('child_process').exec; 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; util.print(data); }); }); }); }); node-temp-0.8.1/lib/000077500000000000000000000000001237002057200141545ustar00rootroot00000000000000node-temp-0.8.1/lib/temp.js000066400000000000000000000146211237002057200154630ustar00rootroot00000000000000var fs = require('fs'), os = require('os'), path = require('path'), cnst = require('constants'); var rimraf = require('rimraf'), rimrafSync = rimraf.sync; /* HELPERS */ var RDWR_EXCL = cnst.O_CREAT | cnst.O_TRUNC | cnst.O_RDWR | cnst.O_EXCL; var generateName = function(rawAffixes, defaultPrefix) { var affixes = parseAffixes(rawAffixes, defaultPrefix); var now = new Date(); var name = [affixes.prefix, now.getYear(), now.getMonth(), now.getDate(), '-', process.pid, '-', (Math.random() * 0x100000000 + 1).toString(36), affixes.suffix].join(''); return path.join(affixes.dir || exports.dir, name); }; var parseAffixes = function(rawAffixes, defaultPrefix) { var affixes = {prefix: null, suffix: null}; if(rawAffixes) { switch (typeof(rawAffixes)) { case 'string': affixes.prefix = rawAffixes; break; case 'object': affixes = rawAffixes; break; default: throw new Error("Unknown affix declaration: " + affixes); } } else { affixes.prefix = defaultPrefix; } return affixes; }; /* ------------------------------------------------------------------------- * Don't forget to call track() if you want file tracking and exit handlers! * ------------------------------------------------------------------------- * When any temp file or directory is created, it is added to filesToDelete * or dirsToDelete. The first time any temp file is created, a listener is * added to remove all temp files and directories at exit. */ var tracking = false; var track = function(value) { tracking = (value !== false); return module.exports; // chainable }; var exitListenerAttached = false; var filesToDelete = []; var dirsToDelete = []; function deleteFileOnExit(filePath) { if (!tracking) return false; attachExitListener(); filesToDelete.push(filePath); } function deleteDirOnExit(dirPath) { if (!tracking) return false; attachExitListener(); dirsToDelete.push(dirPath); } function attachExitListener() { if (!tracking) return false; if (!exitListenerAttached) { process.addListener('exit', cleanupSync); exitListenerAttached = true; } } function cleanupFilesSync() { if (!tracking) { return false; } var count = 0; var toDelete; while ((toDelete = filesToDelete.shift()) !== undefined) { rimrafSync(toDelete); count++; } return count; } function cleanupFiles(callback) { if (!tracking) { if (callback) { callback(new Error("not tracking")); } return; } var count = 0; var left = filesToDelete.length; if (!left) { if (callback) { callback(null, count); } return; } var toDelete; var rimrafCallback = function(err) { if (!left) { // Prevent processing if aborted return; } if (err) { // This shouldn't happen; pass error to callback and abort // processing if (callback) { callback(err); } left = 0; return; } else { count++; } left--; if (!left && callback) { callback(null, count); } }; while ((toDelete = filesToDelete.shift()) !== undefined) { rimraf(toDelete, rimrafCallback); } } function cleanupDirsSync() { if (!tracking) { return false; } var count = 0; var toDelete; while ((toDelete = dirsToDelete.shift()) !== undefined) { rimrafSync(toDelete); count++; } return count; } function cleanupDirs(callback) { if (!tracking) { if (callback) { callback(new Error("not tracking")); } return; } var count = 0; var left = dirsToDelete.length; if (!left) { if (callback) { callback(null, count); } return; } var toDelete; var rimrafCallback = function (err) { if (!left) { // Prevent processing if aborted return; } if (err) { // rimraf handles most "normal" errors; pass the error to the // callback and abort processing if (callback) { callback(err, count); } left = 0; return; } else { count; } left--; if (!left && callback) { callback(null, count); } }; while ((toDelete = dirsToDelete.shift()) !== undefined) { rimraf(toDelete, rimrafCallback); } } function cleanupSync() { if (!tracking) { return false; } var fileCount = cleanupFilesSync(); var dirCount = cleanupDirsSync(); return {files: fileCount, dirs: dirCount}; } function cleanup(callback) { if (!tracking) { if (callback) { callback(new Error("not tracking")); } return; } cleanupFiles(function(fileErr, fileCount) { if (fileErr) { if (callback) { callback(fileErr, {files: fileCount}) } } else { cleanupDirs(function(dirErr, dirCount) { if (callback) { callback(dirErr, {files: fileCount, dirs: dirCount}); } }); } }); } /* DIRECTORIES */ function mkdir(affixes, callback) { var dirPath = generateName(affixes, 'd-'); fs.mkdir(dirPath, 0700, function(err) { if (!err) { deleteDirOnExit(dirPath); } if (callback) { callback(err, dirPath); } }); } function mkdirSync(affixes) { var dirPath = generateName(affixes, 'd-'); fs.mkdirSync(dirPath, 0700); deleteDirOnExit(dirPath); return dirPath; } /* FILES */ function open(affixes, callback) { var filePath = generateName(affixes, 'f-'); fs.open(filePath, RDWR_EXCL, 0600, function(err, fd) { if (!err) { deleteFileOnExit(filePath); } if (callback) { callback(err, {path: filePath, fd: fd}); } }); } function openSync(affixes) { var filePath = generateName(affixes, 'f-'); var fd = fs.openSync(filePath, RDWR_EXCL, 0600); deleteFileOnExit(filePath); return {path: filePath, fd: fd}; } function createWriteStream(affixes) { var filePath = generateName(affixes, 's-'); var stream = fs.createWriteStream(filePath, {flags: RDWR_EXCL, mode: 0600}); deleteFileOnExit(filePath); return stream; } /* EXPORTS */ // Settings exports.dir = path.resolve(os.tmpDir()); exports.track = track; // Functions exports.mkdir = mkdir; exports.mkdirSync = mkdirSync; exports.open = open; exports.openSync = openSync; exports.path = generateName; exports.cleanup = cleanup; exports.cleanupSync = cleanupSync; exports.createWriteStream = createWriteStream; node-temp-0.8.1/package.json000066400000000000000000000013111237002057200156700ustar00rootroot00000000000000{ "name": "temp", "description": "Temporary files and directories", "tags": [ "temporary", "temp", "tempfile", "tempdir", "tmpfile", "tmpdir", "security" ], "version": "0.8.1", "author": "Bruce Williams ", "directories": { "lib": "lib" }, "engines": [ "node >=0.8.0" ], "main": "./lib/temp", "dependencies": { "rimraf": "~2.2.6" }, "keywords": [ "temporary", "tmp", "temp", "tempdir", "tempfile", "tmpdir", "tmpfile" ], "devDependencies": {}, "repository": { "type": "git", "url": "git://github.com/bruce/node-temp.git" }, "scripts": { "test": "node test/temp-test.js" } } node-temp-0.8.1/test/000077500000000000000000000000001237002057200143655ustar00rootroot00000000000000node-temp-0.8.1/test/temp-test.js000066400000000000000000000067201237002057200166520ustar00rootroot00000000000000var assert = require('assert'); var path = require('path'); var fs = require('fs'); var util = require('util'); var temp = require('../lib/temp'); temp.track(); var existsSync = function(path){ try { fs.statSync(path); return true; } catch (e){ return false; } }; // Use path.exists for 0.6 if necessary var safeExists = fs.exists || path.exists; var mkdirFired = false; var mkdirPath = null; temp.mkdir('foo', function(err, tpath) { mkdirFired = true; assert.ok(!err, "temp.mkdir did not execute without errors"); assert.ok(path.basename(tpath).slice(0, 3) == 'foo', 'temp.mkdir did not use the prefix'); assert.ok(existsSync(tpath), 'temp.mkdir did not create the directory'); fs.writeFileSync(path.join(tpath, 'a file'), 'a content'); temp.cleanupSync(); assert.ok(!existsSync(tpath), 'temp.cleanupSync did not remove the directory'); mkdirPath = tpath; }); var openFired = false; var openPath = null; temp.open('bar', function(err, info) { openFired = true; assert.equal('object', typeof(info), "temp.open did not invoke the callback with the err and info object"); assert.equal('number', typeof(info.fd), 'temp.open did not invoke the callback with an fd'); fs.writeSync(info.fd, 'foo'); fs.closeSync(info.fd); assert.equal('string', typeof(info.path), 'temp.open did not invoke the callback with a path'); assert.ok(existsSync(info.path), 'temp.open did not create a file'); temp.cleanupSync(); assert.ok(!existsSync(info.path), 'temp.cleanupSync did not remove the file'); openPath = info.path; }); var stream = temp.createWriteStream('baz'); assert.ok(stream instanceof fs.WriteStream, 'temp.createWriteStream did not invoke the callback with the err and stream object'); stream.write('foo'); stream.end("More text here\nand more..."); assert.ok(existsSync(stream.path), 'temp.createWriteStream did not create a file'); var tempDir = temp.mkdirSync("foobar"); assert.ok(existsSync(tempDir), 'temp.mkdirTemp did not create a directory'); // cleanupSync() temp.cleanupSync(); assert.ok(!existsSync(stream.path), 'temp.cleanupSync did not remove the createWriteStream file'); assert.ok(!existsSync(tempDir), 'temp.cleanupSync did not remove the mkdirSync directory'); // cleanup() var cleanupFired = false; // Make a temp file just to cleanup var tempFile = temp.openSync(); fs.writeSync(tempFile.fd, 'foo'); fs.closeSync(tempFile.fd); assert.ok(existsSync(tempFile.path), 'temp.openSync did not create a file for cleanup'); // run cleanup() temp.cleanup(function(err, counts) { cleanupFired = true; assert.ok(!err, 'temp.cleanup did not run without encountering an error'); assert.ok(!existsSync(tempFile.path), 'temp.cleanup did not remove the openSync file for cleanup'); assert.equal(1, counts.files, 'temp.cleanup did not report the correct removal statistics'); }); var tempPath = temp.path(); assert.ok(path.dirname(tempPath) === temp.dir, "temp.path does not work in default os temporary directory"); tempPath = temp.path({dir: process.cwd()}); assert.ok(path.dirname(tempPath) === process.cwd(), "temp.path does not work in user-provided temporary directory"); for (var i=0; i <= 10; i++) { temp.openSync(); } assert.equal(process.listeners('exit').length, 1, 'temp created more than one listener for exit'); process.addListener('exit', function() { assert.ok(mkdirFired, "temp.mkdir callback did not fire"); assert.ok(openFired, "temp.open callback did not fire"); assert.ok(cleanupFired, "temp.cleanup callback did not fire"); });