Baner Baner - 1 year ago 70
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.'/file',function(req,res){
var fstream;
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/uploads/' + filename);
fstream.on('close', function () {
fs.readFile(__dirname + '/uploads/' + filename, "utf-8", function (err, data) {
if (err) throw err;
// data will contain your file contents

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


Answer Source

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))

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

            return resolve(fs.createReadStream(filteredLines));

        rl.on('error', (err) => {
            return reject(err);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download