Baner Baner - 5 months ago 18
Javascript Question

How to read specific data from an uploaded txt file on node js

I need a client to upload a text file. Then I want to parse the text file such that only lines with the word "object" in it is the only thing left in the text file. I have successfully coded the uploading part. But need help coding how to parse out the lines with "object" not in it. My node js code is below.

app.post('/file',function(req,res){
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/uploads/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
fs.readFile(__dirname + '/uploads/' + filename, "utf-8", function (err, data) {
if (err) throw err;
// data will contain your file contents
console.log(data)

// delete file
fs.unlink(__dirname + '/uploads/' + filename, function (err) {
if (err) throw err;
console.log('successfully deleted ' + __dirname + '/uploads/' + filename);
});
});
});

});

Answer

You can use the ReadLine API that's part of Node Core to iterate through the file line-by-line. You can use string.includes() to determine if your line contains the phrase you're looking for.

var readline = require('readline');
var fs = require('fs');

function filterFile(phrase, input) {
    return Promise((resolve, reject) => {
        var lines = [];
        let rl = readline.createInterface({
            input: input
        });

        rl.on('line', (line) => {
            if (line.includes(phrase, 0))
                lines.push(line);
        });

        rl.on('close', () => {
            let filteredLines = Buffer.from(lines);

            return resolve(fs.createReadStream(filteredLines));
        });

        rl.on('error', (err) => {
            return reject(err);
        });
    });
}