Узел JS: Ошибка загрузки файла [ERR_STREAM_WRITE_AFTER_END] - PullRequest
0 голосов
/ 15 октября 2019

Итак, я пытаюсь сделать так, чтобы я просто загружал файлы в определенную папку с помощью nodeJS с помощью Formidable Module, используя следующую ссылку. Загрузка файла с использованием nodeJS

Теперь мой файл загружается в нужную мне папку, но, поскольку я запускаю команду из CLI, она выдает мне ошибку

Вот код , который я пробовал:

var http = require('http') ;
var formidable = require('formidable') ;
var fs = require('fs');


http.createServer(function(req, res){
if(req.url == '/fileUpload'){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err,fields,files){
        var oldpath = files.filetoupload.path;
        var newpath = 'C://xampp/htdocs/nodejs/upload/' + files.filetoupload.name;
        fs.rename(oldpath, newpath, function (err){
            if(err) throw err;
            res.write('File Uploaded and Moved !!');
            res.end();
        });
        res.write('File Uploaded');
        res.end();
    });
}
else{
    res.writeHead(200, {'Content-Type': 'text/html'}) ;
    res.write('<form action="fileUpload" method = "post" enctype="multipart/form-data">');
    res.write('<input type = "file" name="filetoupload" /><br/>') ;
    res.write('<input type="submit" />') ;
    res.write('</form>') ;
    return res.end() ;
    }
}).listen(8080) ;

Ошибка Я получаю:

> Error [ERR_STREAM_WRITE_AFTER_END]: write after end
>     at write_ (_http_outgoing.js:572:17)
>     at ServerResponse.write (_http_outgoing.js:567:10)
>     at C:\xampp\htdocs\nodejs\upload.js:14:8
>     at FSReqWrap.args [as oncomplete] (fs.js:140:20) Emitted 'error' event at:
>     at writeAfterEndNT (_http_outgoing.js:634:7)
>     at process._tickCallback (internal/process/next_tick.js:63:19)

1 Ответ

3 голосов
/ 15 октября 2019

Вы пытаетесь писать после закрытия потока.


    var form = new formidable.IncomingForm();
    form.parse(req, function(err,fields,files){
        var oldpath = files.filetoupload.path;
        var newpath = 'C://xampp/htdocs/nodejs/upload/' + files.filetoupload.name;
        fs.rename(oldpath, newpath, function (err){
            if(err) throw err;
            res.write('File Uploaded and Moved !!');
            res.end(); // here, remove this end call
        });
    });

...