How can I connect/add a text file to my JS script

Question would be, how can I add a text file that includes a string to my js file, I want to check the repeated words in a string and keep a count in JavaScript, but I have no idea how to add text file to my js script.

My JS script is like this:

let words = "Awesome Javascript coding woohoo";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));

So I would like to add my text file (named TextFile2.txt) that contains:

"Awesome Javascript coding woohoo woohoohoho";

to then from inside my JS script and my text file string would be printed out, instead printing out:

let words = "Awesome Javascript coding woohoo";

Answer

I assume you want to do this from browser, there is no mention for nodejs environment, so my answer will reflect a browser solution.

You can access any file with an input[type=file] element and tap the File api, there you will find the .text() promise to return the file contents.

The File interface doesn’t define any methods, but inherits methods from the Blob interface.

Browser solution: :

var words = "";

function countRepeatedWords(sentence) {
  let words = sentence.split(" "); // i would change it to sentence.split(/(s|t)+/);
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

// This function is called when the input has a change
function fileContents(element) {

  var file = element.files[0];
  file.text().then(text => {
    words = text; // update words
    // run your function 
    console.log(countRepeatedWords(words));
  })
}
<html>

<body>
  <input type="file" name="readThis" id="readThis" onChange="fileContents(this)" />
</body>

</html>

Node.JS solution:

const {readFile, readFileSync} = require('fs');

let file = '/path/to/your/file';

let words = "";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

// Synchronous example
words = readFileSync(file).toString(); // convert buffer to string
console.log('Synchronous',countRepeatedWords(words));

// Asynchronous example
readFile( file, 'utf8' , (err, data)=> {
  
  if( err ){
    console.log(err);
  }else{
     
    words = data; // update words
    
    console.log('Asynchronous',countRepeatedWords(words));
  }

});