JavaScript: How to read a local file (specifically a json file)? - javascript

My question is very simple:
I'd like to read a configuration json file relying on the front end side and not on the server.
The file name and path is hard-coded in the JS file.
I am not the getting its name from some file dialog like in many examples on SO.
I also tried some suggestions to use fetch like:
fetch('./data/properties.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(error));
but I always got errors like
exh.js:30 Fetch API cannot load
file:///C:/Users/myusername/WebAppsProjects/BBSimFE/data/properties.json.
URL scheme must be "http" or "https" for CORS request.
I also installed and CORS Chrome extension and turned it on => no help.
I also tried to understand whether I can use FileReader.
For example:
var fr = new FileReader();
fr.readAsText(new File([""], "./data/properties.json"));
fr.onload = function(evt){
alert(fr.result);
}
But this returns nothing.
Also, I am not using node.js so I cannot use require();
Please assist.
Thanks

For security purposes, fetch does not work for file urls, so opening your file in the browser won't work. You should set up a local testing server so XHR requests work properly. Some options include running python -m http.server 8080 in the directory that your files are in then navigating to http://localhost:8080 in the browser, or using a plugin like vscode's live server plugin.

Hey) For security purposes you should not store important configuration info on your frontend side. It should be on server side.
But if you store not important info in your config file, you need to lift a server on localhost, port may be any. Also you need to do your folder with config.json is static on server side. After that you have a static folder with needed for you files, at current case it's config.json. On frontend side you need send
fetch('http://localhost:<your_port>/static/config.json', options);
if you set your static folder is static if no then replace static by your static folder name. You can check if your static file is available just go http://localhost:<your_port>/static route and you should see all files|folders inside static folder.

Related

How to find full path when sending a file over a post request from Next JS functions (server)?

In the Next JS server-side pages/api, I have a function that makes a post request to a service requiring two files.
I am trying to read these files using the following code:
var fullPhotoPath = process.cwd() + '/public/photos/photo.png'
var photoStream = fs.createReadStream(fullPhotoPath)
This works when I run the app locally, but it fails with file not found error when deployed.
I assume the pathing in server changes because of webpack, though I am not familiar with NextJS.
Things I have tried:
Use relative path
Move photo files to different locations either public or private folders
Deploy in different environments: same error in both Firebase or Vercel hosting.
Workaround with getStaticProps/getServerSideProps: can't send file to API functions since they aren't JSON-able.
Thanks for suggestions.

How to read xml file content with vuejs Server side?

I need to read a xml file storaged in a specifice path in server side.. I am using the VueJS and I can-t use JQUERY... could you help me with some idea or advice?
Case:
1. The file will be storage in /static/label/custom-label.xml
2. I need to read this file of the server side and load the contect.
3. I will use the content loaded in a const.
Not sure what backend you're using, but it's flagged as JS so I'll assume Node/Express. Correct me if I'm wrong.
Use express middleware to define your paths. If you're storing assets on your server for public consumption, store them in your /public/ folder.
app.use('/static', express.static('public'));
app.use(express.static('files'));
Use /static/ route to get static resources
http://localhost:3000/static/foobar.jpg
https://expressjs.com/en/starter/static-files.html
This SO post may help: Read remote file with node.js (http.get)

Access a local directory to retrieve files from localhost and write back

I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.

Load html file in typescript

I have an html file in the same directory of the typescript file. IO have to load it and return it from the function.
public ...(... ) : angular.IHttpPromise<string> {
...
return $http({
method: 'GET',
url: 'help.html'
});
Error: NetworkError: 404 Not Found - http://localhost:3000/help.html
The directory does not matter. Why?
The typescript file is actually javascript and this runs on the browser ie. the client's machine and not your server. The client has no clue what the structure is on the server so placing these files in the same folder is a convenience for the developer and nothing more.
The HTM / HTML file is hosted on your server and the server knows nothing about the client.
To fix it - You have to specify the path to your html file in the $http command so the server knows where to pick it up from. The path always starts at the root of the folder that is hosted by IIS (or appache or whatever). So if you are hosting it in a folder named someFolder in the root of the web site folder then your url that you would use in the typescript file would be /someFolder/help.html.
If you want to manually test that the url is correct you should be able to put it directly in the URL of your web browser (along with the host) and it should return the content.

socket.io.js not loading

I know there are a bunch of questions on this already, but none have answered it for me, and plus mine is slightly different.
I'm starting the socket.io server in node using this:
var io = require('socket.io').listen(8000);
My terminal says everything is ok:
info - socket.io started
Now I am trying to load the .js file in my clientside browser using this url:
http://<hostname>:8000/socket.io/socket.io.js
I dont get a 404, it just hangs forever. I've also used a network utility to ping port 8000, and it seems to be open fine.
I installed node and socket.io just yesterday, so they should be the latest versions. Can anyone shed any light on this? Thanks!
Turns out the reason I could never request the .js file was because my company network blocks all ports except the usual ones (80, 21, etc), so `I would never be able to communicate with port 8000.
Use express.js. Place the socket.io file in public/javascripts folder and add this line to your html
<script src="/javascripts/socket.io.js"></script>
I think this is the best way. When you're writing http://<hostname>:8000/socket.io/socket.io.js
node tries to find a folder named socket.io in your project's public folder. And the file socket.io.js in it.
If you don't want to use express.js you should catch the request and try to load a file if no routes were found for your request (what actually express does) because node doesn't know what to do for requests which don't match any routes in your server.
And I recommend to use the socket.io.min.js file (it's smaller and it's in folder node_modules\socket.io\node_modules\socket.io-client\dist)
You have to start an http/https server to access it via http/https. Simply starting an socket.io server won't do. Do the following:
var http = require('http');
var app = http.createServer(),
io = require('socket.io').listen(app);
app.listen(7000, "0.0.0.0");
Then I can access the file http://localhost:7000/socket.io/socket.io.js
sockets.io uses websocket protocol (ws://). See the wikipedia page.
You need to get at least 3 pieces working together.
Serve some HTML (/index.html will do just fine) so there's a web page. This file should contain the socket.io client <script> tag. For this you need the http server portion of the starter examples. You are missing this and that's why browsing to your server just hangs.
Serve the socket.io client. Socket.io will do this for you automatically when you pass in your http server function to it. You don't need full express as this can be done with just node's http module as per the first example on the socket.io docs.
Some javascript to actually do something with the socket. This can be the content of a <script> tag in index.html or a separate file. If it's a separate file, you need to set up your http server to actually serve it.

Categories