Ben February 2016

NodeJS File Creation as an Object?

I dont want to save the file locally, but I want to create a file object which is then uploaded through an API.

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

    var arr = [
     [4, 56, 7, 3, 345],
     [34, 5, 2, 5, 7]
       ];

    var r = requests.post("https://slack.com/api/files.upload", function(err, res,body){
       console.log(body)''
     }

     var form = r.form();
     form.append('token', token)
     form.append("filename", filename)
     form.append('file', new Buffer(arr));

I want to know if its possible to not save the file locally and just add in the file with the data to the form to be submitted through the API?

Answers


peteb February 2016

Yes, you can pipe the file directly into the request without saving the value. However, it depends on where the data is coming from and how you can access it. When you do fs.createReadStream('<filepath>') you're creating a ReadStream that you pass to request as part of your form data. Request then uses this Stream to read the file and pass it through to the resource you just requested.

The below code, will take a file that is accessible to the server and will pass it through request to the desired endpoint.

var request = require('request');
var fs = require('fs');

var formData = {
  token: token,
  filename: filename,
  file: fs.createReadStream('<filepath>');
};

request({
  method: 'POST',
  url: 'https://slack.com/api/files.upload',
  form: formData
}, function(err, res, body) {
   console.log(JSON.stringify(body, null, 2));
});

Post Status

Asked in February 2016
Viewed 2,723 times
Voted 5
Answered 1 times

Search




Leave an answer