Error using Fs.createReadStream('file') to save a file to a formData() in Node

Asked

Viewed 102 times

0

Hello, I try to save a file inside a formData() in nodejs, but when I check, Fs.createReadStream('file') says that 0 bytes were read. Could someone explain to me why this is happening? And if possible suggest a solution. Follow the code part:

let form = new FormData()
form.append('My_file', fs.createReadStream('arquivo.json'));
axios.post('URL_Qualquer', form)
         .then(response => { 
             console.log(response)
         })
         .catch(error => {
             console.log(error.response)
       });

1 answer

0


It’s probably not finding the.json file. You are passing the correct path to your.json file. ?

  • yes, I’m quite sure

  • Then use the following functions: //Event to read the file. ( If you have something) read_stream.on('data', Function(Chunk) { data += Chunk; }); // Text end event. read_stream.on('end',Function(){ // content console. console.log("Stream data is : " + data); });

  • Sorry my ignorance, but I didn’t understand it right. Is to use this "read_stream.on()" to read the file? passing the path on the date?

  • Hi, sorry it took so long. var read_stream = Fs.createReadStream('.json file'); //Event to read the file. ( If you have something ) read_stream.on('data', Function(Chunk) { data += Chunk; }); // Text end event. read_stream.on('end',Function(){ // content console. console.log("Stream data is : " + data); });

  • in case what would be the 'date' inside read_stream.on() ? When executing this code I get: data is not defined

  • data is the variable where you will store the data. I will send you a URL to make you more successful. https://www.dev2qa.com/node-js-stream-example/

  • opa, I could read the file like this

  • Well, it’s right there ?

  • the reading of the file was done correctly, thank you very much. But at the part where I request with the api to send the file I keep getting the error that the file was not read. Even if its contents appeared on the console.log()

  • you are using asynchronous functions to wait for reading the file and then upload the contents ?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.