Ad
How To Make Fs.readFile Just Back Lines Inner The Scopes?
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad