codebased
codebased

Reputation: 7073

Uploading document in NodeJs using Fs module : Error: write after end

I have been trying to upload a document using the following code.

I did googled and could not find any solution as yet.

app.post('/documents', function (req, res) {

    var document = {};

    var fstream = null;

    // populate fields
    form.on("field", function (name, value) {
        document[name] = value ;

    });

    form.on("part", function (part) {

        if (!part.filename) {
            return;
        }

        var path = __dirname + '/files/' + part.filename;

         fstream = app.npm.fs.createWriteStream(path);

        document.type = part.headers["content-type"]
        document.name = part.filename;
        document.size = part.byteCount;
        document.path = path;

        fstream.on("close", function () {
            db.sequelize.models.Document.create(document).then(function (newDocument) {
                    res.send(newDocument)
                    res.end();
                },
                function (error) {
                    res.send(error);
                });
        });
        part.pipe(fstream);

    });

    form.on("close", function (data) {

        fstream.end();
        fstream = null;

    });

    form.parse(req);
});

NOTE: I am using fs module. https://nodejs.org/api/fs.html

The first image works ok. but when I try to upload an another image, it throws an exception:

events.js:72 throw er; // Unhandled 'error' event ^

Error: write after end at writeAfterEnd (_stream_writable.js:132:12) at Form.Writable.write (_stream_writable.js:180:5) at write (_stream_readable.js:601:24) at flow (_stream_readable.js:610:7) at IncomingMessage.pipeOnReadable (_stream_readable.js:642:5) at IncomingMessage.emit (events.js:92:17) at emitReadable_ (_stream_readable.js:426:10) at emitReadable (_stream_readable.js:422:5) at readableAddChunk (_stream_readable.js:165:9) at IncomingMessage.Readable.push (_stream_readable.js:127:10)

Upvotes: 2

Views: 952

Answers (1)

codebased
codebased

Reputation: 7073

Found the solution.

var form = new app.npm.multiparty.Form();

This was defined at global level. Where as for every new request I should be creating a new instance of the form because stream is off in the previous call so I should create a new instance by getting latest contents.

The solution looks likes:

app.post('/documents', function (req, res) {

var document = {};

var form = new app.npm.multiparty.Form();

var fstream = null;

...

And the rest is same.

Upvotes: 7

Related Questions