Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

node.js

tmp

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;
}
like image 335
Doug Avatar asked Nov 09 '15 22:11

Doug


People also ask

How do I write to a file in node?

The easiest way to write to files in Node. js is to use the fs. writeFile() API.

What are node buffers?

In Node. js, buffers are a special type of object that can store raw binary data. A buffer represents a chunk of memory - typically RAM - allocated in your computer. Once set, the size of a buffer cannot be changed. A buffer stores bytes.


1 Answers

In short, you don't. The point of this module is precisely to guess the system's default temporary directory, generate random file names and handle the file and directory removal for you.

In that sense it's quite opinionated about where to save and using a specific file name, you can only specify a folder name within the system's temporary directory and prefix / postfix options.

About writing contents to the file, you have to handle it yourself:

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");
});

Other modules like temp or temporary work in similar manner.

like image 89
cviejo Avatar answered Sep 20 '22 00:09

cviejo