How do I extract text from txt files into one CSV file?

I have a folder full of .txt files. Within each text file, there is a line that says the following:

Name: [name here]

So for example, the first three text files could contain Bob Smith, Joe Snow, or Mary Fields in the “Name” field (in the place of [name here]).

Further, I’d like to create a column called “text” that contains all the contents within each .txt file (e.g., in the text column for 1.txt, it will say “Name: Bob Smith”).

I’d like to extract the names into a CSV file that looks like this:

file_name, name, text
1.txt, Bob Smith, Name: Bob Smith
2.txt, Joe Snow, Name: Joe Snow
3.txt, Mary Fields, Name: Mary Fields

This is the JS solution that I’ve tried:

const fs = require('fs');

const files = fs.readdirSync('./').filter((file) => /.txt$/.test(file));
if (!files.length) process.exit(1);

const text = fs.readFileSync('./');
if (!files.length) process.exit(1);

fs.writeFileSync('names.csv', 'file_name, name\n, text');

files.forEach((file) => {
  const match = fs.readFileSync(file, { encoding: 'utf8' }).match(/^(.*?)[,\/] Name:/mi);
  if (match && match[1]) {
    fs.appendFileSync('names.csv', `${file}, ${match[1]}\n, ${text}`);
  }
});

It is currently outputting a file called “names.csv” but it does not contain the text from the file. I suspect it’s an issue with the const text part, but I’m having trouble identifying or remediating the error.

Alright, so do you have any questions? Errors?

Sorry, I just added the issue on my original post. Basically, it is currently outputting a file called “names.csv” but it does not contain the text from the file. I suspect it’s an issue with the const text part, but I’m having trouble identifying or remediating the error.