-1

In a nutshell, what I want is for a javascript function to check a file for an HTML input. I have tried using doing as this post told me to: Javascript check if (txt) file contains string/variable
But kept getting an error saying ReferenceError: fs is not defined
So now I am here asking for help.

6
  • fs for node not for browser. Commented Apr 3, 2020 at 17:30
  • Is this helpful? stackoverflow.com/questions/45405517/module-fs-cannot-be-found Commented Apr 3, 2020 at 17:30
  • 3
    Hi Kaiden, your question could benefit from some example source code. For future reference please review stackoverflow.com/help/how-to-ask Commented Apr 3, 2020 at 17:32
  • You might just need to import fs. At the top of your script add: const fs = require('fs'); Commented Apr 3, 2020 at 17:36
  • So understanding that I cannot use fs, but what can I do then? Commented Apr 3, 2020 at 17:37

2 Answers 2

1

I cannot be sure because you didn't provide any example code, but fs usually refers to "file system" in nodejs So the answer from the other topic isn't complete but the import is implied by it's usage:

var fs = require("fs")

fs.readFile(FILE_LOCATION, function (err, data) {
  if (err) throw err;
  if(data.indexOf('search string') >= 0){
   console.log(data)
  }
});

But like some other commentors have said, this is for nodejs and not in the browser.

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

3 Comments

data.includes answers the question more directly than indexOf and might be more performant.
@rayhatfield searching for a string in a file (txt file as example) not a string in a string.
@KaidenSmith I'm referring to his use of indexOf in the callback, where data is a string or buffer, both of which support includes.
0

If you're trying to do this in a browser, you could fetch the url and use includes to check for the string you're looking for:

async function responseContains(url, string) {
  try {
    const content = await fetch(url).then(response => response.text());
    return content.includes(string);
  }
  catch (e) {
    console.log(e);
    throw e;
  }
}

const url = 'https://jsonplaceholder.typicode.com/todos/1';
/*
  the url above returns:
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
*/

responseContains(url, 'userId')
  .then(found => console.log(`Found 'userId'? ${found}`));
// Found? true

responseContains(url, 'wookies with bananas')
  .then(found => console.log(`Found 'wookies with bananas'? ${found}`));
// Found? false

Comments

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.