Fede E.
Fede E.

Reputation: 1918

NodeJS Process Uploaded file with readline

I'm getting a file the client uploads which I receive with the following route:

app.post('/upload', function(req, res){
    var file = req.files.file;

    //Process file inline
    funcs.Process(file, req).then((data)=>{
        //res.setHeader('Content-Length', stat.size);
        res.setHeader('Content-Type', 'text/plain');
        res.setHeader('Content-Disposition', 'attachment; filename=output.txt');
        res.write(data, 'binary');
        res.end();
    }).catch((err)=>{
        res.redirect('/?err='+err);
    });

});

This is the code for funcs.Process:

Process: function(file, req){


    return new Promise(function(resolve, reject){

        var lineReader = require('readline').createInterface({
            input: fs.createReadStream(file)
        });

        var output = "";

        lineReader.on('line', function (line) {
            //some checks
            ProcessLine(line).then((data)=>{
                output += data + "\n";
            }).catch((err)=>{
                reject(`Invalid line in file [${line}].`);
            });
        });

        lineReader.on('close', () => {
            resolve(output);
        });

    });

However, I am getting the following error:

TypeError: path must be a string or Buffer,

produced by the readline input: fs.createReadStream(file)

As this is an uploaded file, how do I use it in the readline createInterface?

Upvotes: 0

Views: 343

Answers (1)

Vasan
Vasan

Reputation: 4956

createReadStream accepts a string path.

You're passing it req.files.file, which is the file object created by express-fileupload.

You have two options:

  1. Use the mv function (req.files.file.mv('<path>', callbackFunc)) to first move the file to a known path on your server. Then pass this known path to fs.createReadStream.

  2. Create the read stream directly from the file data buffer exposed in req.files.file.data using streamifier or similar library.

var fileStream = require('streamifier').createReadStream(req.files.file.data)

This stream can then be passed to readline as input directly.

Upvotes: 2

Related Questions