我需要臨時將一個文件寫入文件系統,以便對其進行快速檢查,然後再刪除它。如何使用Node tmp Package從緩衝區寫入文件
根據我的谷歌搜索,它看起來像tmp目錄軟件包可以的NodeJS可以使用: https://www.npmjs.com/package/tmp
但我真的被文檔混淆。
這是他們就如何使用它來創建一個臨時文件的例子:
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();
});
但是,當我讀到的是,它看起來像它的傳遞函數爲tmp.file。我如何將緩衝區,路徑或其他東西傳遞給它來做它的事情並創建臨時文件?
我必須錯過一些愚蠢的東西。
感謝您的幫助!
-------------最終答案------------------------------- ------------------
想象我會發布我的最終答案,以防在閱讀示例代碼時幫助其他人以某種方式發生了大腦阻塞。這應該是顯而易見的,現在我看到了問題。謝謝你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;
}
Cviejo,謝謝你。我在想這完全錯了。不敢相信我以前沒有看到過。實際上,我在一個小時前剛剛注意到它,並且剛剛完成了代碼的工作。不知何故,我被困在事實上,我需要傳遞的東西,實際上我只是需要與我給的東西一起工作。 – Doug
正是。 Tbh,它也花了我一些時間來消化,對於大多數情況下,你真的不需要你自己的文件夾.. – cviejo