Search code examples
javascriptrequire

Why is require module in JavaScript not able to import the fs library?


The javascript code is as follows:

const fs = require('fs');

function init() {
     alert("Done!");
}

init();

While executing the Javascript code, I am not able to get the alert Done! on my webpage. On further analysis I came to a conclusion that it is most probably because the require statement is not working (there was an alert when I commented the require statement). Why is it so?


Solution

  • require is not available in the browser but is used in NodeJS. If you want to use it in your browser, you'll need a building tool like Browserify or Webpack.

    By the way, the File System package is available in NodeJS only.