I need to write a file temporarily to the file system in order to run a quick check on it, and I then want it deleted.
Based on my Googling, it looks like the tmp package for NodeJS can be used: https://www.npmjs.com/package/tmp
But I'm really confused by the documentation.
This is the example they give on how to use it to create a temporary file:
var tmp = require('tmp');
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
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();
});
But when I read that, it looks like its passing a function into tmp.file. How do I pass a buffer, a path, or something into this for its to do its thing and create the temporary file?
I must be missing something silly.
Thank-you for your help!
------------- Final Answer -------------------------------------------------
Figured I'd post my final answer in case it helped someone else who somehow had a brain block when reading the example code. This should have been obvious now that I see the problem. Thank-you CViejo.:
var fs = require('fs');
var Q = require('q');
var tmp = require('tmp');
self=this;
/**
* writeBufferToFile - Takes a buffer and writes its entire contents to the File Descriptor location
* @param fd - File Decripter
* @param buffer - Buffer
* @returns {*|promise} - true if successful, or err if errors out.
*/
module.exports.writeBufferToFile = function(fd, buffer){
var deferred = Q.defer();
fs.write(fd, buffer, 0, buffer.length, 0, function (err, written, buffer){
if(!written)
deferred.reject(err);
else
deferred.resolve(true);
});
return deferred.promise;
}
/**
* writeBufferToTempFile - Takes a buffer and writes the entire contents to a temp file
* @param buffer - The buffer to write out.
* @returns {*|promise} - The file path of the file if a success, or the error if a failure.
*/
module.exports.writeBufferToTempFile = function(buffer){
var deferred = Q.defer();
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err)
deferred.reject(err);
else {
self.writeBufferToFile(fd, buffer).then(
function (isWritten) { deferred.fulfill(path); },
function (err) { deferred.reject(err); });
}
});
return deferred.promise;
}