Giter Club home page Giter Club logo

Comments (23)

anseki avatar anseki commented on June 1, 2024

Hi @DEYROS, thank you for the comment.
Now you can use await operator to get it from Promise instance like a synchronous execution style.
Also, you can specify crlfDelay option for reading line by line.

const rl = readline.createInterface({
  input: fileStream,
  crlfDelay: Infinity
});

for await (const line of rl) {
  // Do something
  console.log(line);
}

https://nodejs.org/api/readline.html

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Hi @anseki thx for your help,
I tried this :

var lineReader = require('readline').createInterface({ //Readline = module natif à NodeJS
    input: require('fs').createReadStream(tabFichiers[i]), //Open the file in which we are "tabFichiers[i]" in the form of a readable stream
    crlfDelay: Infinity
});

fs.open('fichierConcath7.md', 'w', function (err, file) { // Creation of an empty markdown file which will contain the whole tree
    if (err) throw err;
});

for await (const line of lineReader) {
    let dieses = '#'.repeat(profondeur - 1); //Repeat # according to depth (EX: depth 2 = ##)
    //If the line contains a # and the depth is greater than one and it is not an index.md
    if (line.includes('#') && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
        line = dieses.concat(line); //We concatenate with sharps
        let hCombien = line.count("#"); //We count the number of #
        
    //If the line contains a # and the depth is greater than one and it is an index.md
    }else if (line.includes('#') && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
        line = dieses.concat(line); //We concatenate with sharps
        line = line.replace(/^./, ""); // We remove the first character which is a # since index is always one hash less
        let hCombien = line.count("#"); //We count the number of #
    }
    
    fs.appendFileSync('fichierConcath7.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
        if (err) throw err;                                        
    });
}

But it doesn't work and I got this ERROR :
image

I did something wrong ?

from readline-sync.

anseki avatar anseki commented on June 1, 2024

That is JavaScript syntax error.
You mistook usage await operator.
Replace the for await (const line of lineReader) {...} with:

(async () => {
  for await (const line of lineReader) {
    ...
  }
})();

See document for the await operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

image
🤔

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024
async () => {
    for await (const line of lineReader) {
        let dieses = '#'.repeat(profondeur - 1); //Repeat # according to depth (EX: depth 2 = ##)
        //If the line contains a # and the depth is greater than one and it is not an index.md
        if (line.includes('#') && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
            line = dieses.concat(line); //We concatenate with sharps
            let hCombien = line.count("#"); //We count the number of #
            
        //If the line contains a # and the depth is greater than one and it is an index.md
        }else if (line.includes('#') && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
            line = dieses.concat(line); //We concatenate with sharps
            line = line.replace(/^./, ""); // We remove the first character which is a # since index is always one hash less
            let hCombien = line.count("#"); //We count the number of #
        }
        
        fs.appendFileSync('fichierConcath7.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
            if (err) throw err;                                        
        });
    }
};

I don't have any error with that but my file "fichierConcath7.md" is empty

from readline-sync.

anseki avatar anseki commented on June 1, 2024

No, read this again:
#112 (comment)

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Ok so, I've done this :

let stockProf = [];//array that stores all depths

// library
const glob = require("glob");  
const fs = require('graceful-fs'); 

// Function that allows you to count the number of times a character is present
// Lets you know the depth
String.prototype.count = function (c) {
    var result = 0, i = 0; // Initialize the result and i to zero
    for (i; i < this.length; i++)if (this[i] == c) result++; //Add +1 each time there is the character you are looking for
    return result; //We return the result which is the number of times there is the character
};

function parcoursDossier(src, callback) {
    glob(src + '/**/*', callback);
};

parcoursDossier('SpringCore', function (err, tabFichiers) {
    if (err) {
        console.log('Erreur', err);
    } else {
        let tailleTab = tabFichiers.length; //Takes the size of the arrFiles array

        if (!tailleTab >= 1) { //If there is not 1 or more folders/files in it then the folder does not exist so ERROR
            console.log("Dossier à parcourir non trouvé ou vide !")
        } else { //If the file given in the parameters of the pathFolder function then exists:
            for (let i = 0; i < tailleTab; i++) { //Browse files/folders
                let profondeur = 0; //Initialize the depth to 0

                try {
                    //If (tabFichiers[i]) is a Markdown file or a folder
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md") || fs.lstatSync(tabFichiers[i]).isDirectory()) { 
                        profondeur += tabFichiers[i].count("/"); //Take the number of "/" there are in the name of the current folder / file
                        stockProf.push(profondeur); // Add a depth in array that stores all depths
                    }
                    
                    //If it's a Markdown file
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) { 
                        
                        var lineReader = require('readline').createInterface({ //Readline = module natif à NodeJS
                            input: require('fs').createReadStream(tabFichiers[i]), //Open the file in which we are "tabFichiers[i]" in the form of a readable stream
                            crlfDelay: Infinity
                        });
                        
                        fs.open('fichierConcath7.md', 'w', function (err, file) { // Creation of an empty markdown file which will contain the whole tree
                            if (err) throw err;
                        });

                        (async () => {
                            for await (var line of lineReader) {
                                let dieses = '#'.repeat(profondeur - 1); //Repeat # according to depth (EX: depth 2 = ##)
                                //If the line contains a # and the depth is greater than one and it is not an index.md
                                if (line.includes('#') && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    let hCombien = line.count("#"); //We count the number of #
                                    
                                //If the line contains a # and the depth is greater than one and it is an index.md
                                }else if (line.includes('#') && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    line = line.replace(/^./, ""); // We remove the first character which is a # since index is always one hash less
                                    let hCombien = line.count("#"); //We count the number of #
                                }
                                
                                fs.appendFileSync('fichierConcath7.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
                                    if (err) throw err;                                        
                                });
                            }
                        })();

                    }
                } catch (err) {
                    console.error("Erreur" + err); 
                }
            }
            console.log("Profondeur max : " + Math.max(...stockProf)); //Returns the maximum value of the array that stores all depths
        }
    }
});

But I get the same result as before(which is not good). Did I make a mistake somewhere?

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

The last file in my tree looks like this :
image

When I don't read line by line I get this:
image
Which is prefect and I was doing it like that :

for (let i = 0; i < tailleTab; i++) {
        let profondeur = -2; //Initialise la profondeur à -2

        try {
          if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md") || fs.lstatSync(tabFichiers[i]).isDirectory()) { //Si c'est un fichier Markdown ou un dossier
            profondeur += tabFichiers[i].count("/"); //Prend le nombre de / qu'il y a dans le nom du dossier 

            stockProf.push(profondeur); // Ajouter une profondeur dans tableau qui stocks toutes les profondeurs
          }
          if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) { //Si c'est un fichier Markdown
            let contenu = fs.readFileSync(tabFichiers[i], 'utf8'); //Prend le contenu du fichier et ajoute dans contenuFichiers
            contenuFichiers += contenu + "\n"; //Prend le contenu du fichier et ajoute dans variable super globale contenuFichiers
          }
        } catch (err) {
          console.error("Erreur" + err); //Affiche l'erreur qu'on catch
        }
      }
      console.log("Profondeur max : " + Math.max(...stockProf)); // Renvoie la valeur maximum du tableau qui stocks toutes les profondeurs
      fs.writeFile('fichierConcat.md', contenuFichiers, function (err) { //Créer un fichier avec "contenuFichiers" ou remplace le contenu avec "contenuFichiers" si le fichier est déjà créé
        if (err) throw err; // Si il y a une erreur renvoie erreur
        console.log("Fichier .Md Créé, création du Pdf depuis le Markdown..."); //Affiche que le fichier est créé et que le pdf ce créé
        //exec('npx mdpdf fichierConcat.md'); //Execute la commande de la biblio mdpdf sur le fichier qu'on a créé avec writeFile
      });

But as I said I need to reed it line by line to make an "h1" title in depth 0 stay in h1 but an "h1" title in depth 1 becomes an h2.

But when I read it line by line here is what I get at the last lines :
image

But this lines are here in my tree :
image

from readline-sync.

anseki avatar anseki commented on June 1, 2024

Sorry, my English is poor.
Do you mean that the issue about reading lines was solved?
And, did new issue about file contents come?

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Hello, not at all. Even with await that you gave me :

 (async () => {
                            for await (var line of lineReader) {
                                let dieses = '#'.repeat(profondeur - 1); //Repeat # according to depth (EX: depth 2 = ##)
                                //If the line contains a # and the depth is greater than one and it is not an index.md
                                if (line.includes('#') && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    let hCombien = line.count("#"); //We count the number of #
                                    
                                //If the line contains a # and the depth is greater than one and it is an index.md
                                }else if (line.includes('#') && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    line = line.replace(/^./, ""); // We remove the first character which is a # since index is always one hash less
                                    let hCombien = line.count("#"); //We count the number of #
                                }
                                
                                fs.appendFileSync('fichierConcath7.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
                                    if (err) throw err;                                        
                                });
                            }
                        })();

It's async because I have the same result with "readline" which is async. And I want it sync to read line by line my files to put them in one markdown file in order. Thx !

from readline-sync.

anseki avatar anseki commented on June 1, 2024

Hmm... Why did you regard that as async by only the result?
Sorry, I couldn't understand what you want to do, but your code has several bugs maybe because that has many strange lines, e.g. fs.appendFileSync(s1, s2, func), strange style, includes instead of endsWith, etc.
Also, why do you want the sync?

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Hello @anseki !

I have a big tree of markdown files that I walk through and turn into a single markdown file. I would like to make an "h1" title in depth 0 stay in h1 but an "h1" title in depth 1 becomes an h2.

First I was doing it like this :

//Superglobal variable called contenuFichiers 
let contenuFichiers = "";

const fs = require('fs');
const glob = require("glob"); //Utilise la biblio "glob" pour l'installer :  >npm i glob    

// Function that allows you to count the number of times a character is present
// Lets you know the depth
String.prototype.count = function (c) {
  var result = 0, i = 0;// Initialize the result and i to zero
  for (i; i < this.length; i++)if (this[i] == c) result++;//Add +1 each time there is the character you are looking for
  return result;//We return the result which is the number of times there is the character
};

function parcoursDossier(src, callback) {
  glob(src + '/**/*', callback);
};
let stockProf = [];//array that stores all depths
parcoursDossier('springcore', function (err, tabFichiers) {
  if (err) {
    console.log('Erreur', err);
  } else {
    let tailleTab = tabFichiers.length; //Takes the size of the array tabFichiers
    if (!tailleTab >= 1) { //If there is not 1 or more folders/files in it then the folder does not exist so ERROR
      console.log("Dossier à parcourir non trouvé !")
    } else { //If the file given in the parameters of the pathFolder function exist:
      for (let i = 0; i < tailleTab; i++) {
        let profondeur = 0; //Initialize the depth to 0

        try {
          if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md") || fs.lstatSync(tabFichiers[i]).isDirectory()) { //If it's a Markdown file or a folder
            profondeur += tabFichiers[i].count("/"); //Take the number of "/" there are in the name of the current folder / file
            stockProf.push(profondeur); // Add a depth in array that stores all depths
          }

          if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) { //If it's a Markdown file
            let contenu = fs.readFileSync(tabFichiers[i], 'utf8'); //Takes the content of the file and adds in "contenu"
            contenuFichiers += contenu + "\n"; //Take the content of the file and add it to the super global variable contenuFichiers
          }
        } catch (err) {
          console.error("Erreur" + err); //Displays the error we catch
        }
      }
      console.log("Profondeur max : " + Math.max(...stockProf)); //Returns the maximum value of the array that stores all depths
      fs.writeFile('fichierConcat.md', contenuFichiers, function (err) { //Create a file with "contenuFichiers" or replace the content with "contenuFichiers" if the file is already created
        if (err) throw err; 
      });
    }
  }
});

Everything is perfect, I have the elements in the right order but then I realized that I had to go through the contents of the files in my tree structure line by line to have the depth and to detect the titles (when there was "#"). So I did this :

let stockProf = [];//array that stores all depths

// library
const glob = require("glob");  
const fs = require('graceful-fs'); 

// Function that allows you to count the number of times a character is present
// Lets you know the depth
String.prototype.count = function (c) {
    var result = 0, i = 0; // Initialize the result and i to zero
    for (i; i < this.length; i++)if (this[i] == c) result++; //Add +1 each time there is the character you are looking for
    return result; //We return the result which is the number of times there is the character
};

function parcoursDossier(src, callback) {
    glob(src + '/**/*', callback);
};

parcoursDossier('SpringCore', function (err, tabFichiers) {
    if (err) {
        console.log('Erreur', err);
    } else {
        let tailleTab = tabFichiers.length; //Takes the size of the arrFiles array

        if (!tailleTab >= 1) { //If there is not 1 or more folders/files in it then the folder does not exist so ERROR
            console.log("Dossier à parcourir non trouvé ou vide !")
        } else { //If the file given in the parameters of the pathFolder function then exists:
            for (let i = 0; i < tailleTab; i++) { //Browse files/folders
                let profondeur = 0; //Initialize the depth to 0

                try {
                    //If (tabFichiers[i]) is a Markdown file or a folder
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md") || fs.lstatSync(tabFichiers[i]).isDirectory()) { 
                        profondeur += tabFichiers[i].count("/"); //Take the number of "/" there are in the name of the current folder / file
                        stockProf.push(profondeur); // Add a depth in array that stores all depths
                    }
                    
                    //If it's a Markdown file
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) { 
                        
                        var lineReader = require('readline').createInterface({ //Readline = module natif à NodeJS
                            input: require('fs').createReadStream(tabFichiers[i]), //Open the file in which we are "tabFichiers[i]" in the form of a readable stream
                            crlfDelay: Infinity
                        });
                        
                        fs.open('fichierConcath7.md', 'w', function (err, file) { // Creation of an empty markdown file which will contain the whole tree
                            if (err) throw err;
                        });

                        (async () => {
                            for await (var line of lineReader) {
                                let dieses = '#'.repeat(profondeur - 1); //Repeat # according to depth (EX: depth 2 = ##)
                                //If the line contains a # and the depth is greater than one and it is not an index.md
                                if (line.includes('#') && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    let hCombien = line.count("#"); //We count the number of #
                                    
                                //If the line contains a # and the depth is greater than one and it is an index.md
                                }else if (line.includes('#') && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
                                    line = dieses.concat(line); //We concatenate with sharps
                                    line = line.replace(/^./, ""); // We remove the first character which is a # since index is always one hash less
                                    let hCombien = line.count("#"); //We count the number of #
                                }
                                
                                fs.appendFileSync('fichierConcath7.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
                                    if (err) throw err;                                        
                                });
                            }
                        })();

                    }
                } catch (err) {
                    console.error("Erreur" + err); 
                }
            }
            console.log("Profondeur max : " + Math.max(...stockProf)); //Returns the maximum value of the array that stores all depths
        }
    }
});

But when I read it line by line here is what I get at the last lines :
image

But this lines are here in my tree :
image

It should not be at the end of my file. I don't know what am I supposed to do, I am completly new to the async and sync function.

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

And I don't understand where are the strange lines ? Why "fs.appendFileSync(s1, s2, func)" is a "strange style" ? And I wan't to know if there is a # in my line so includes is great isn't it ?

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

I tried this :

//If it's a Markdown file
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) {
                        
                        var rd = readline.createInterface({
                            input: fs.createReadStream(tabFichiers[i])
                        });

                        rd.on('line', function(line) {
                            console.log(line);
                        });
                    }

which gave me this :
image
So it's not working If i am writing into the console because I should have this :
image
But if i am doing only this :

//If it's a Markdown file
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) {
                        
                        var rd = readline.createInterface({
                            input: fs.createReadStream(tabFichiers[i]),
                            output: process.stdout,
                            console: false 
                        });
                    }

It will work because I got this in the console :
image

from readline-sync.

anseki avatar anseki commented on June 1, 2024

I see...
First of all, you seem to be mistaking the synchronous execution.
Try this:

  1. Save this text to a file named test01.txt.
A
B
C
D
E
  1. Save this code to a file named test01.js at same directory.
'use strict';

const fs = require('fs'),
  readline = require('readline');

console.log('CALL async function');
(async () => {

  const rl = readline.createInterface({
    input: fs.createReadStream('test01.txt'),
    crlfDelay: Infinity
  });

  console.log('START');

  let cnt = 0;
  for await (const line of rl) {
    console.log(`L#${++cnt}: ${line}`);
  }

  console.log('FINISH Lines:', cnt);

})();
console.log('CALLED async function');
  1. Do this command at same directory:
node test01.js

Then, result should be:

CALL async function
START
CALLED async function
L#1: A
L#2: B
L#3: C
L#4: D
L#5: E
FINISH Lines: 5

This means the code was executed synchronously. If the result was another, it was not synchronously.

So, your code is strange structure, and it seems that the writing each file is executed synchronously, and reading files is executed asynchronously. That is, there is the code out of the async function.
Read the example code above, and find the await operator in async function is synchronous. The reading files in your code is not. Also, note that the "CALLED async function" is not the last.

fs.appendFileSync doesn't work with invalid arguments.
See document: https://nodejs.org/api/fs.html#fsappendfilesyncpath-data-options

Also, there are many errors in your code. If you are using VS Code, you can check the report of the errors. In my environment, VS Code reported 132 errors in your code. E.g. push Ctrl + Shift + M keys.
And also, the String.prototype.count is very wrong way... BTW, don't you want to count # only at start of line?
And also, why you don't use "glob" to find ".md" files? You got all files by using the "glob", and after that, you found ".md" files by using includes (you should use endsWith instead). That is, the "glob" is not required for your code.
And also, and also, and also... Sorry, I couldn't understand all of your code...

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Ok so I got this result :
CALL async function
START
CALLED async function
L#1: A
L#2: B
L#3: C
L#4: D
L#5: E
FINISH Lines: 5

So the code was executed synchronously ! When I push Ctrl + Shift + M keys I have this :
image

I tried this but i got the same issue and as you can see in my code appendFileSync have the same result as console.log.

'use strict';
let stockProf = [];//array that stores all depths

// library
const glob = require("glob");  
const fs = require('fs'),
  readline = require('readline');

// Function that allows you to count the number of times a character is present
// Lets you know the depth
String.prototype.count = function (c) {
    var result = 0, i = 0; // Initialize the result and i to zero
    for (i; i < this.length; i++)if (this[i] == c) result++; //Add +1 each time there is the character you are looking for
    return result; //We return the result which is the number of times there is the character
};

function parcoursDossier(src, callback) {
    glob(src + '/**/*', callback);
};

parcoursDossier('SpringCore', function (err, tabFichiers) {
    if (err) {
        console.log('Erreur', err);
    } else {
        let tailleTab = tabFichiers.length; //Takes the size of the "tabFichiers" array which is the array with all the files of SpringCore

        fs.open('fichierConcatTest.md', 'w', function (err, file) { 
            if (err) throw err;
        });

        if (!tailleTab >= 1) { //If there is not 1 or more folders/files in it then the folder does not exist so ERROR
            console.log("Dossier à parcourir non trouvé ou vide !")
        } else { //If the file given in the parameters of the pathFolder function then exists:
            for (let i = 0; i < tailleTab; i++) { //Browse files/folders
                let profondeur = 0; //Initialize the depth to 0

                try {
                    //If (tabFichiers[i]) is a Markdown file or a folder
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md") || fs.lstatSync(tabFichiers[i]).isDirectory()) { 
                        profondeur += tabFichiers[i].count("/"); //Take the number of "/" there are in the name of the current folder / file
                        stockProf.push(profondeur); // Add a depth in array that stores all depths
                    }
                    
                    //If it's a Markdown file
                    if (fs.lstatSync(tabFichiers[i]).isFile() && tabFichiers[i].includes(".md")) { 
                        
                        (async () => {

                            const rl = readline.createInterface({
                              input: fs.createReadStream(tabFichiers[i]),
                              crlfDelay: Infinity
                            });
                          
                            let cnt = 0;
                            for await (const line of rl) {
                                /* console.log(`L#${++cnt}: ${line}`);  */// same result as appendFileSync()
                                fs.appendFileSync('fichierConcatTest.md', line + "\n", function (err) { 
                                 if (err) throw err;                                         
                                });
                            }
                          
                        })();

                    }
                } catch (err) {
                    console.error("Erreur" + err);
                }
            }
            console.log("Profondeur max : " + Math.max(...stockProf)); //Returns the maximum value of the array that stores all depths
        }
    }
});

Yes I would like to count the # at the beginning of the lines but why is String.prototype.count a bad way to do it?
I don't understand why the library "glob" isn't required ? Without it I can't take all the folders/files of my folder "SpringCore".
How would you use "glob" to find ".md" files?
Do you have any idea how I could do to get the code in order?
I really appreciate your help, I'm starting to understand a little better THANK YOU!

from readline-sync.

anseki avatar anseki commented on June 1, 2024

Maybe your VS Code has not set up with ESLint.
See this attached image. And you should set up it.
ss-01

You should not change the String.prototype.
See this: https://www.google.com/search?q=prototype+pollution
Now many environments of ECMAScript prohibit that. Therefore your code doesn't work in many environments maybe.

Your code counts all # in a line (not the start of the line also).
For example, you can use RegExp for that easily. (one-line)

const line = '### Header Foo #5 URL: https://example/#bar';
// Count `#`
const countHead = /^(#*)/.exec(line)[1].length;
console.log('H-level:', countHead);

Your code counts all / to get the depth but that may be incorrect result.
For example, these point the same directory:

dir1/dir2/dir3
dir1/dir2/dir3/

But your code gets 2 and 3.
For example, you can count segments to get correct result. (one-line)

const path = 'dir1/dir2//dir3/';
// Count Path segments
const countSegments = path.split(/[/\\]+/).filter(segment => !!segment).length;
console.log('Path segments:', countSegments);

You can get .md files by glob("**/*.md", ...).
https://www.npmjs.com/package/glob
You can solve the issues by reading document.

from readline-sync.

anseki avatar anseki commented on June 1, 2024

If the await is hard for you, you can read all lines of each file and process it line by line.
For example:

const fs = require('fs');
// Read a file
const path = './test01.txt',
  contents = fs.readFileSync(path, {encoding: 'utf8'});
console.log('START');
contents.split(/[\n\r]+/).forEach(line => {
  // Do something
  console.log(`LINE: ${line}`);
});
console.log('FINISH');

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Hello @anseki ! It finally work !
Could you explain me what does this line exactly :

const countSegments = path.split(/[/\\]+/).filter(segment => !!segment).length;

And also this one ?

contents.split(/[\n\r]+/).forEach(line => {

Everything in my folder is perfect but there is no more spaces between the lines. I am totaly new to RegExp.
Thank you again !

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

I have done this which work as I wan't but there is no more spaces between the lines as I said it.

const contents = fs.readFileSync(tabFichiers[i], {encoding: 'utf8'});
                        contents.split(/[\n\r]+/).forEach(line => {
                            /* console.log(`LINE: ${line}`); */
                            let dieses = '#'.repeat(profondeur - 2); //Répète # en fonction de la profondeur (EX : profondeur 2 = ##)
                            if (/^(#*)/.exec(line)[1].length && profondeur >= 1 && !tabFichiers[i].includes('_index.md')){ 
                                line = dieses.concat(line); //On concatene avec dieses
                                
                            //Si la ligne contient une # et que la profondeur est supérieur à un et que c'est un index.md
                            }else if (/^(#*)/.exec(line)[1].length && profondeur >= 1 && tabFichiers[i].includes('_index.md')){ 
                                line = dieses.concat(line); //On concatene avec dieses 
                                line = line.replace(/^./, ""); //On enlève le premier caractères qui est un # vu que index à toujours une dièse de moins
                            }
                            fs.appendFileSync('fichierConcatTest.md', line + "\n", function (err) { //appendFile() adds content to the end of a file
                                if (err) throw err;                                        
                            });
                        });

If I am doing this instead :

contents.split(/[]+/).forEach(line => {

There will be spaces between lines but only the first title with # will be processed.

from readline-sync.

anseki avatar anseki commented on June 1, 2024

For example, when a path dir1/dir2///dir3/ is passed, your code returns incorrect result because it counts /. The example code that I showed counts path segments such as dir1 instead. In other words, that counts all directories in the path.

Does the "spaces between the lines" mean empty lines? And do you mean that you want to keep the empty lines?
If so, use this instead.

contents.split(/\r\n|\n|\r/).forEach(line => {

BTW, your code counts the # multiple times wastefully. You can do that only once and save the result.
For example:

const count = /^(#*)/.exec(line)[1].length;
if (count) { ...
 :
 :
if (count > 3) { ...

And also, the tabFichiers[i].includes('_index.md') too.

const isIncluded = tabFichiers[i].includes('_index.md');

from readline-sync.

DEYROS avatar DEYROS commented on June 1, 2024

Thank you @anseki !

from readline-sync.

anseki avatar anseki commented on June 1, 2024

😄

from readline-sync.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.