I'm trying to upload images to the server. I use the extension "multer". Here is an example of the file saving code:

var file = req.files.image, path = __dirname + '/uploads/'; var buffer = file.buffer, //Note: buffer only populates if you set inMemory: true. fileName = file.name; var stream = fs.createWriteStream(path + fileName); stream.on('error', function(err) { console.log('Could not write file to memory.'); res.status(400).send({ message: 'Problem saving the file. Please try again.' }); }); stream.on('finish', function() { console.log('File saved successfully.'); var data = { message: 'File saved successfully.' }; res.jsonp(data); }); stream.write(buffer); stream.end(); console.log('Stream ended.'); 

The problem is that the "finish" event does not work. Although the file is saved normally, that is, it is physically created, the content is recorded. But the event is not called that the recording is completed.

I have little experience with NodeJS, so I ask for help, how can I localize the problem and understand what is wrong?

In general, there is a need for such an event as "finish"? That is, after calling stream.write(buffer); at the beginning the file will be recorded, and then the program will continue with the next instruction?

I dug, if I understood correctly, then the "finish" event is present from version 0.10 in NodeJS. I use 0.8. How can I determine in this case that the recording of the file is completed and I can send a response to the browser?

Thank.

    1 answer 1

    Something I'm not sure that

     stream.on('finish', function() { 

    relevant to this design.

    I recommend to consider this example of understanding.

    • The event "finish" I took from the example on the Internet. Slightly misunderstood the example of your link, it turns out req.pipe (stream); says that when the work on file writing is completed, the event will be triggered by req.on ('end', function {? But my "end" event is not called again either, it turns out I cannot find out that the recording is complete. - walik
    • In general, there is a need for such an event as "finish"? That is, after calling stream.write(buffer); at the beginning the file will be recorded, and then the program will continue with the next instruction? - walik
    • I dug, if I understood correctly, then the "finish" event is present from version 0.10 in NodeJS. I use 0.8. How can I determine in this case that the recording of the file is completed and I can send a response to the browser? - walik
    • docs.nodejitsu.com/articles/file-system/ ... and give the result to the server callback, for example. - deivan_