1

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";
5
  • declare those variables at the top of the function scope, not inside the for loop please Commented Sep 1, 2021 at 16:59
  • Load it through ajax, or use some server-side programming. Commented Sep 1, 2021 at 17:02
  • 1
    Does this answer your question? How do I load the contents of a text file into a javascript variable? Commented Sep 1, 2021 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). Commented Sep 1, 2021 at 17:04
  • There are many duplicates to how to read a text file in Node as well... Commented Sep 1, 2021 at 20:11

4 Answers 4

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

});

Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, forgot to add that I'am trying to use the Node.js environment, could you help with that?
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.
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
@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.
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?
|
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.

5 Comments

If you need any doubt let me know.
What framework/language is this? It doesn't look like Node...
this is javascript code for access the file content.
PHP doesn't have let nor console.log or .split
JavaScript does not have fread, flength, or fopen functions.
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.

Comments

0
function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};
  
  words.forEach(word => {
    wordMap[word] = (wordMap[word] || 0) + 1;
  });
  
  return wordMap;
}

let sentence = "Awesome Javascript coding woohoo";
console.log(countRepeatedWords(sentence));
...

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
code without explanation is not so useful. Next time, please add an explanation where it solves the problem. In this case, I see no solution to the problem how to use the contents of a text file, so it does not anser the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.