0

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";
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • declare those variables at the top of the function scope, not inside the for loop please – AGE Sep 01 '21 at 16:59
  • Load it through ajax, or use some server-side programming. – Heretic Monkey Sep 01 '21 at 17:02
  • 1
    Does this answer your question? [How do I load the contents of a text file into a javascript variable?](https://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable) – Heretic Monkey Sep 01 '21 at 17:03
  • 2
    The answer to this question is completely different depending on your JavaScript environment (that is, Node vs. a browser vs. something else). – Pointy Sep 01 '21 at 17:04
  • There are many duplicates to how to read a text file in Node as well... – Heretic Monkey Sep 01 '21 at 20:11

3 Answers3

1

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));
  }

});
darklightcode
  • 2,738
  • 1
  • 14
  • 17
  • Sorry, forgot to add that I'am trying to use the Node.js environment, could you help with that? – Eero Jyrgenson Sep 01 '21 at 17:24
  • I have updated my answer with a node.js example, both synchronous and asynchronous. My advice is if you're new to nodejs, sync methods might be tempting, but use sync methods only when your app starts to do things such as loading/writing configs before you start the main function. In your main function use an async approach or else your app will hang badly on the long-term. – darklightcode Sep 01 '21 at 17:36
  • on Node.js im getting this kind of error, but to my knowledge I typed the path file correctly.. C:\Users\eeroj\source\repos\Nodejs\pish\pish>node appblin.js internal/fs/utils.js:314 throw err; ^ eposNodejspishpish'uch file or directory, open 'C:Userseerojsource – Eero Jyrgenson Sep 01 '21 at 17:47
  • @EeroJyrgenson it seems that you don't escape those backwards slashes, it should be like this `C:\\path\\to\\yourfile`, you can replace with forward slashes, it also works `C:/path/to/yourfile`. – darklightcode Sep 01 '21 at 17:51
  • Yes!! thank you so much, okay I learned alot from this now. also is there a possible way to code it like it would list the words in an alphabetical order? – Eero Jyrgenson Sep 01 '21 at 18:00
  • @EeroJyrgenson You are encroaching onto "help vampire" territory, where you ask one question, then continually ask for more and more from the answerer until they are bled dry. Please do some research (which would have found how to read a text file in Node.js quite readily), then, if you really can't find anything, ask a new question. – Heretic Monkey Sep 01 '21 at 20:12
0

So you can first open the file and write the connect according to requirement. If you want to read the previous connect then you can use :

Read str = fread(file,flength(file) ;

file = fopen("c:\MyFile.txt", 3);// opens the file for writing fwrite(file, str);// str is the content that is to be written into the file.

Vishwa
  • 1
  • 2
0

You can read a text file by using filesystem aka fs. Reading a text file would look something like this.

Text File named "TextFile2.txt":

Awesome Javascript coding woohoo woohoohoho

And the JavaScript file would contain this:

const fs = require('fs')

fs.readFile('TextFile2.txt', 'utf8', (err, data) => {
    if (err) {
        console.error(err)
        return
    }
    console.log(data)
})

The data variable is the text inside the text file. You can manipulate or do whatever with it.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122