-2

I was trying to display a text that was read from a file on my client-side HTML. But when I use require 'fs' it doesn't work because of security concerns. Is there any way to read a file stored on a server using fs then display it on the client-side. A rough sketch of what I'm trying to do is attached below but it doesn't work because I get error require is not defined. Any help is appreciated thanks in advance.

const fs = require('fs')
const data = fs.readFileSync('filePath', 'utf-8')
<p id="insertHere" style="color: white;"></p>

<script> document.getElementById("insertHere").innerHTML = data;</script>
anon20010813
  • 155
  • 7
  • [require is not defined](https://stackoverflow.com/a/31931648/11926970) please read these answers. Now you said, ***"But when I use require 'fs' it doesn't work because of security concerns."*** What security concerns you are talking about? – Not A Bot Apr 28 '21 at 09:24
  • you can't read and write a file from client-side in js because of security concerns how clearer can it get. @NotABot – anon20010813 Apr 28 '21 at 09:26

2 Answers2

2

JavaScript running in the web browser cannot have access to the file system on the server.

Imagine if you could open your browser's developer tools while using your online banking and just start reading files from your bank's hard disk!

If you want to get a file from the server to client-side JS you need to do something on both sides.

On the server you need to make the file available over HTTP(S). This could be as simple as putting the file somewhere under the DocumentRoot of the web server.

On the client you need to make an HTTP request. You can do that using the fetch API, the XMLHttpRequest API or a library that wraps one of them such as Axios.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

require() modules can only be used with NodeJS. Install NodeJS from https://nodejs.org and write the following code:

const express = require("express");
const fs = require("fs");
const app = express();

app.get("/", (req, res) => {
       const data = 
   fs.readFileSync('filePath', 'utf8'); //or try the asynchronous method 
   res.send(`<p style='color: white'>${data}</p>`);
});

app.listen(3000, () => {
    console.log("Server is running on port 3000!");
});

Now, navigate to http://localhost:3000/ in your browser, and see the result.