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

Dou*_*oug 7 file tmp node.js

我需要临时写一个文件到文件系统,以便快速检查它,然后我想删除它.

根据我的谷歌搜索,看起来可以使用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();
});
Run Code Online (Sandbox Code Playgroud)

但是当我读到它时,它看起来像是将一个函数传递给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;
}
Run Code Online (Sandbox Code Playgroud)

cvi*_*ejo 15

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

从这个意义上说,对于保存和使用特定文件名的位置非常苛刻,您只能在系统的临时目录和前缀/后缀选项中指定文件夹名称.

关于将内容写入文件,您必须自己处理:

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"));
    // fs.appendFile(path, "random text");
});
Run Code Online (Sandbox Code Playgroud)

其他模块,如临时临时工作,类似的方式.