The "temp" package is a versatile tool for handling temporary files, directories, and streams in Node.js. It is specially engineered to generate unique file or directory names under the system's temporary directory, change the file mode accordingly, and even provide automatic removal of the temporary entities if needed. This package offers a similar API to the Node.js 'fs' module and is well-suited to the demands of scripts, task runners like Grunt, and even long-running server processes.
Utilizing "temp" involves the use of different methods depending on the nature of your task. If you want to create a temporary file, the open
or openSync
method can be used with optional prefix, suffix, or both. A temporary directory can be created using mkdir
or mkdirSync
, or you can use path
to get a unique name in the system temporary directory. If you want to track the temporary files and directories for automatic cleanup, call the track
method. To trigger cleanup at any time, use cleanup
or cleanupSync
. Below are some examples to illustrate these methods:
For creating and writing to a temporary file and cleaning it up automatically:
var temp = require('temp'),
fs = require('fs');
temp.track();
var myData = "sample data";
temp.open('myprefix', function(err, info) {
fs.write(info.fd, myData, (err) => {
console.log(err);
});
fs.close(info.fd, function(err) {
// do something with the file
});
});
For creating a temporary directory:
var temp = require('temp'),
fs = require('fs'),
path = require('path'),
temp.track();
var myData = "Hello World";
temp.mkdir('mydir', function(err, dirPath) {
fs.writeFile(path.join(dirPath, 'myfile.txt'), myData, function(err) {
// do something with the file
});
});
The documentation for "temp" is encompassed in the package's README content. It provides comprehensive detail about the package's functionalities, methods, affixes handling, and examples to guide you. For more information, you can visit the official GitHub repository at 'http://github.com/bruce/node-temp'. Please make sure to review the examples directory, as it contains working copies of the example usage provided in the readme.