skip to Main Content

I need help with my nodejs code

const fs = require('fs');

function processFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const lines = content.split('n');

  const wordIdMaps = lines.map(() => ({ wordIdMap: {}, currentId: 1 }));

  lines.forEach((line, index) => {
    const words = line.split(' ');
    const wordIdMap = wordIdMaps[index].wordIdMap;
    let currentId = wordIdMaps[index].currentId;

    words.forEach((word) => {
      if (!wordIdMap[word]) {
        wordIdMap[word] = currentId;
        currentId++;
      }
    });
  });

  return { lines, wordIdMaps }; // Return both lines and wordIdMaps
}

function customConsoleLog(logFormat, wordIdMaps) {
  const lines = wordIdMaps.map((map) => Object.entries(map.wordIdMap).map(([word, id]) => `${word}:${id}`).join(' '));

  lines.forEach((line, index) => {
    const wordIdMap = wordIdMaps[index].wordIdMap;

    const replacedLog = logFormat.replace(/${(d+)}/g, (_, id) => {
      const word = Object.keys(wordIdMap).find((key) => wordIdMap[key] == id);
      return word !== undefined ? word : '${' + id + '}';
    });

    const words = line.split(' ');
    const replacedLine = replacedLog.replace(/${d+}/g, (match) => {
      const id = match.slice(2, -1);
      return words[id - 1] !== undefined ? words[id - 1] : match;
    });

    console.log(replacedLine);
  });
}

// Command-line arguments
const filePath = process.argv[2];
const logFormat = process.argv[3];

if (!filePath || !logFormat) {
  console.log('Please provide both a file path and a custom console log format as command-line arguments.');
} else {
  const { lines, wordIdMaps } = processFile(filePath);

  customConsoleLog(logFormat, wordIdMaps);
}

This nodejs code takes data from a txt file and provides custom output through command line argument
If I write:

node index.js test.txt '${1} ${2} ${3} ${4}'

The code splits the file content’s lines and then splits the words by whitespace, and provides the output in which it reads and lists first four words of every line of the file content, for example:

apple boy cat dog
elephant fish god hen

But the output creates an extra line of IDs after listing out all the lines

apple boy cat dog
elephant fish god hen
 ${2} ${3} ${4}

How can I fix this error?

2

Answers


  1. As @mandy8055 has already pointed out, it may has to do with an additional empty line including a line break (CR or CRLF or LF).

    I can reproduce your image of error if i add an extra empty line.

    Try debug read the length of the variable lines inside your function processFile – it adds one extra entry!

    To make your code more rubust about this, additional fixes would be:

    1. On line 5: filter out empty lines

    exchange:

    const lines = content.split('n');
    

    with:

    const lines = content.split('n').filter((line)=>{return line 
    != ""});
    
    1. or even one step earlier:
      use .trim() on line 4:
    const content = fs.readFileSync(filePath, 'utf-8').trim();
    
    Login or Signup to reply.
  2. Looks like this line is doing it:

    return word !== undefined ? word : '${' + id + '}';
    

    Try this instead:

    return (word !== undefined) ? word : '';
    

    Not exactly the best error handling, but it suppresses those extraneous tags.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search