Node Fs.js running in HTML

Asked

Viewed 322 times

3

Hello, I need to use Node.js’s Fs function but am encountering errors. When running using Node use_fs.js it runs and works perfectly. However when I put it into html it always says q require is not defined. That is, when I run the console it works and when I put it in the browser it doesn’t work, I know Fs is a core function of Node.js, but when

<script language="javascript">
          var fs = require('fs');
          var fileContent = "Hello World!";
          var filepath = '_folder/file.txt';
          fs.writeFile(filepath, fileContent, function (err) {
            if (err) throw err;
            console.log('Saved!');
          });
    </script>

someone can give a hint?

  • In what context are you running? The browser to access the user’s file system? will not work unless it is a hybrid app with NWJS or Eletron on a siite does not roll no mano

  • Actually, I want to get the sha256 hash of a file and already have the encryption part, but when I test in the browser to access the file, I always get the error of require is not defined.

  • The user (in the browser) cannot access a file on the server unless, you (on the server) make this file available... if it is "expressjs" would be something like express.static() in the path to the file (or in a publish folder). Even if you are using "Browserify" the front-end cannot read the back-end file system this way... it is necessary to use XMLHttpRequest() or fetch() otherwise we can’t.

  • Hello, sorry, I don’t think I made myself understood. The user(in the browser) needs to access a local file(in the user’s pc). But as I’m still testing and it’s all intranet I’m not able to carry.

  • Even though we are in localhost does not work like this, if it is not a hybrid app the browser cannot access the user’s file system programmatically. It will be necessary to use a <input type="file"> and the api File to read the file.

1 answer

1

There is a difference in executing javascript in Nodejs and Browser, in Node the platform maps the operating system libs already in the Browser maps those of the Browser itself, so it will not be possible to use Fs since it is a mapped function for the operating system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.