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
– Lauro Moraes
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.
– Felipe Simões
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 useXMLHttpRequest()
orfetch()
otherwise we can’t.– Lauro Moraes
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.
– Felipe Simões
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 apiFile
to read the file.– Lauro Moraes