Question:
I have a String and I want to convert it to a stream to send it as if it were a file through the request
multipart
.
I want to do it in the air, without generating the file on disk.
I'm doing it this way:
const stream = require("stream")
module.exports = function () {
let readStream = new stream.PassThrough()
readStream.end(new Buffer('<file data>'), () => {
const options = {
url: '<url>',
method: 'POST',
json: true,
formData: {
file: readStream
}
};
request(options, (error, res)=> {
if(error) {
console.log(JSON.stringify(error))
}
});
})
})
}
… and it returns the following error:
{
"code":"BadRequestError",
"message":"MultipartParser.end(): stream ended unexpectedly: state = PART_DATA"
}
Answer:
I can think of 2 ways:
No stream
- Using
formData
ofrequest
we send thecustom_file
.
module.exports = function () {
const options = {
url: '<url>',
method: 'POST',
json: true,
formData: {
custom_file: {
value: '<file data>',
options: {
filename: 'file.txt',
contentType: 'text/plain'
}
}
}
};
let req = request(options, (error, res)=> {
if(error) {
console.log(JSON.stringify(error))
}
})
}
With stream
- Using
Readable
you create astream
of thestring
.
Example:
const Readable = require('stream').Readable
module.exports = function () {
//
let stream = new Readable;
stream._read = function noop() {};
stream.push('<file data>');
stream.push(null); // Indicamos fin del archivo (fin del stream)
const options = {
url: '<url>',
method: 'POST',
json: true,
formData: {
custom_file: {
value: stream,
options: {
filename: 'file.txt',
contentType: 'text/plain'
}
}
}
};
let req = request(options, (error, res)=> {
if(error) {
console.log(JSON.stringify(error))
}
})
}