Ad

How To Make Fs.readFile Just Back Lines Inner The Scopes?

- 1 answer

I use fs.readFile and throw data and get all file lines, now I need just to get lines inner scopes {}

Here's the code:

//index.js
const fs = require('fs');
fs.readFile(process.argv[2], (err, data) =>  {
    if (err) throw err;
    console.log(`${data}`)
});


//app.scss
.app {
 color: black;
  .a {
      margin: 10px;
   }
}

usage

node index.js <CSS file directory> //dummy example

node index.js app.scss //real example

results

//all file lines will print in console
.app {
 color: black;
  .a {
      margin: 10px;
   }
}

expected results

color: black; 
margin: 10px;

But here data is all file lines, I need just back lines inner scopes, any help?

Ad

Answer

Create a function that receives all the lines of the file, a split is made with the line break(\n) so that we can go through line by line, now we only add a set of validations to know when to concatenate and when not.

I leave this example of the operation of the function, which returns an array and a string, I did it this way since I did not know in what way you needed the output. I hope it's useful for you.

// index.js    
const fs = require('fs');

function getData(data) {
    let countOpenCurlyBraces = 0;
    let concatenate = null;
    let stringRes = '';
    const arrRes = [];
    const arr = data.split('\n');
    arr.forEach((element) => {
        if (countOpenCurlyBraces == 0) {
            concatenate = false;
        }
        if (element.includes('{')) {
            countOpenCurlyBraces++;
            concatenate = true;
            return;
        }
        if (element.includes('}')) {
            countOpenCurlyBraces--;
            return;
        }
        if (concatenate) {
            arrRes.push(element.trim());
            stringRes += element.trim() + '\n';
        }
    });
    return {
        arrRes,
        stringRes
    };
}

fs.readFile(process.argv[2], "utf8", (err, data) => {
    if (err) throw err;
    console.log(getData(data).stringRes);
});


// app.scss
//all file lines will print in console
.app {
 color: black;
  .a {
      margin: 10px;
   }
}

results:

color: black;
margin: 10px;
Ad
source: stackoverflow.com
Ad