如何使用 Node tmp 包从缓冲区写入文件

How to use Node tmp Package to write a file from the buffer

我需要将一个文件临时写入文件系统以便运行对其进行快速检查,然后我希望将其删除。

根据我的谷歌搜索,看起来可以使用 NodeJS 的 tmp 包: 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。我如何将缓冲区、路径或其他内容传递给它以执行其操作并创建临时文件?

我一定是漏掉了一些愚蠢的东西。

感谢您的帮助!

------------最终答案---------------------------- ------------------

我想我会 post 我的最终答案,以防它帮助其他人在阅读示例代码时不知何故遇到了大脑障碍。既然我看到了问题,这应该是显而易见的。谢谢 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;
}

简而言之,你没有。该模块的重点恰恰是猜测系统默认的临时目录,生成随机文件名并为您处理文件和目录的删除。

从这个意义上讲,它对保存位置和使用特定文件名很固执,您只能在系统的临时目录和前缀/后缀选项中指定文件夹名称。

关于写入文件的内容,需要自己处理:

var fs  = require("fs");
var tmp = require("tmp");

tmp.file(function (err, path, fd, cleanup) {
    if (err) throw err;

    fs.appendFile(path, new Buffer("random buffer"), function (err) {
      if (err)
        throw err
    });
    // fs.appendFile(path, "random text");
});

temp or temporary 等其他模块以类似方式工作。