Read a local project file when a page is loaded - javascript

I am trying to read a project file that will be updated(occasionally) by me and my website will read it dynamically upon the loading of the page, will i have to build a server for this or can javascript handle it?
If so, could you share code that could achieve this.
Thanks in advance!!!

The problem seems to be how can one:
read a plaintext file stored on the website's local directory
use the contents of the file to modify a web page's content
This could be handled with JavaScript on the server side, but only if the server is configured to run JavaScript (like a node.js server).
Since the original question reads "will i have to build a server for this", it's probably likely that this is a vanilla server like Apache.
Most Apache servers are configured to run PHP code, so PHP is probably the simplest solution for grabbing the plaintext file.
Code below will load the contents of a plaintext file on the server into a JavaScript string, which then can be acted upon in the browser with JavaScript.
This code would go inside a <script> element in the HTML file:
function actUponProjectFile () {
// read project file on server using PHP, and store into JavaScript
// constant `projectFileString`
const projectFileString = `<?php
$pfText = file_get_contents('./my_project_file.txt');
echo $pfText; ?>`;
// insert code to act upon the `projectFileString` here
}
// run `actUponProjectFile()` after the window loads
window.onload = () => {
actUponProjectFile();
}

Save your data in a Javascript file and include it in your html
// data.js
const data = [
{
type: 'airtime',
price: 20,
size: '5GB',
},
{
type: 'electricity',
price: 10,
size: '40mw',
},
];
Then include the file in your html file
<script type="text/javascript" src="data.js"></script>

You can use nginx to share static files and use fetch request in js to get this file from server. If you have only static files you don't need to use server, nginx will be enough for you.

Related

Create and download (html/css/js) files client-side

I've built a code playground (similar to liveweave) using react. the users can save their "code playgrounds" and access them later. (using firebase db) ,this "code playgrounds"are just made of HTML, CSS, and js. I´m trying to add a functionality which allow the user to download a playground, the idea is that it will generate 3 separate files (one for each language in the playground)
1) is there a way to generate (HTML CSS and js) files and populate them with content client-side?
2) if so, would there be any chance to group those files inside a .rar also client-side?
3) if generating these files client-side is not the optimal solution/not possible, how would you approach this problem?
I was thinking maybe in an express server that queries the data from the db and then response with those files, but I would like to try a client-sided solution
Finally decided to use fileSaver.js package
import { saveAs } from "file-saver";
const saveFiles = () => {
var blob = new Blob([makeHtml(getDocumentCode())], {
type: "text/plain;charset=utf-8",
});
saveAs(blob, `${getFileName()}.html`);
};
first, you need to make a blob out of the content of the file, in this case, it was HTML +css +js code, makeHtml function handles how the HTML document is constructed, then just pass that blob to the saveAs function along the name and extension for the file, then you can use saveFiles in response to any event like onClick
<button onClick={saveFile}>Download<button/>

Remove directory content Web dev

I am creating a local web application where I want to be able to clear the content of my directory.
How can I remove the files from a directory without deleting the directory itself?
I need it to be empty.
Is it better to remove the whole dir and create it again?
If javascript can delete directory contents, that would a pretty big security concern. Javascript by itself cannot delete system contents. You can make an AJAX call to the server which in turn can delete the files
For deleting the files of your local system you need a server-side scripting language. Vanilla Js cannot do that for you as it is a client-side scripting language.
If you are using Nodejs, as it is a server side you can definitely do that using unlink() for deleting file asynchronously or use unlinkSync() for deleting file synchronously you can learn about how to use that function here...
Demo code unlinkSync() -
const fs = require('fs');
let filename = "D:\\temp\\temp.zip";
fs.unlinkSync(filename);

Load LOCAL JSON file in an HTML using JS (and jquery and/or AJAX); ANSWER=IMPOSSIBLE

Problem definition:
I am programming one HTML file to be run locally in a user machine NOT FUNCTIONING AS A SERVER.
A user could run this html file locally stored in his computer. The HTML file will generate a table dynamically based on the data stored in his machine locally in a particular folder (which is always the same). This data is a JSON file.
For clarity reasons asume that the JSON file is in the same folder as the HTML file.
I have been reading a lot in the internet and in stack overflow at no avail.
For instance:
a) here with:
$.getJSON("books.json", function(json) {
console.log(json);
//access your JSON file through the variable "json"
});
does not work.
Or using this code:
jQuery.getJSON("data.json", handleJSON);
function handleJSON(result){
jQuery.each(result, printFields);
}
function printFields(i, field){
let row = field.id + " "+field.first_name + " "+field.last_name + " <br>";
jQuery("div").append(row);
}
the console says:
[Error] Failed to load resource: Preflight response is not successful (data.json, line 0)
[Error] XMLHttpRequest cannot load file:///Users/jose/CODE/HTML/ConceptsHTML/example%203/data.json. Preflight response is not successful
There are several other links of Stack overflow that I could put here. None one functions as smoothly as they say they do.
(I am using a MAC and trying the HTMLs in Safari and Chrome)
Ultimately I want of course to pass the JSON to an array to be access in other scripts of the HTML.
Note: There are some solutions where it is said that the local machine has to be run as a server and an Httprequest should be done in the machine. Well I can not do that since the users can only open the html file but nothing can be expected from them as to set the machine as as ever whatsoever.
I would be very very glad If I get a hint as to how to proceed. Right now I don't even know if this is actually possible to do.
thanks a lot
You could just use another JS file and link to it in your HTML file, and then in that JS file just make an object with the data you want.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function fun(){
alert(json.data);
}
</script>
</head>
<body>
<button onclick="fun();">push me</button>
</body>
</html>
JS (json.js):
var json = {
data : "hello world"
};
Linking to a local JSON file cannot be done.
THE ANSWER IS:
IT IS NOT POSSIBLE TO READ LOCAL FILES (FILES IN THE USER MACHINE) WITH HTML DUE TO SECURITY REASONS.
The funny thing is that there are plenty of post telling the contrary.
I UNDERSTAND THAT IF THAT WOULD BE POSSIBLE SENSIBLE DATA MIGHT BE STOLEN.
The improvement for html future versions would be to create a way for the local. User to tell the local browser which local folder is "free" to be accesible by html.
At first, you need to parse loaded json file, because before parsing, the content is just string and you can not handle it.
So please do as below:
function handleJSON(result){
result = JSON.parse(result); // using json.parse function to convert string to a valid json model.
jQuery.each(result, printFields);
}
I hope it will be helped you.

Renaming files in a wordpress folder via jquery / jscript

I am trying to run a script that will run every 5 minutes in a shared hostings wordpress folder that will rename the newest CSV file in that folder.
/wp-content/csv/sample.csv
I tried putting a js file in the folder within that folder and run it.
var fs = require('fs');
function runClear()
{
fs.readdir("", (err, files) => {
files.forEach(file => {
console.log(file);
});
})
}
runClear();
setInterval(runClear, 300*1000);
However, it seems like I got client side and server side scripting confused. It seems like I need node.js.
What would be the best approach for this?
Regards,
Yes you are right you are confused in client side and server side script.
Javascript is a client side script which deal with all the user interactions like what will happen user click something or submit a form, hover over some element, scroll the web page etc.
Where as server side script like php deals with data stored on server like mysql records or the physical files.
what you are trying to do is to change the server resource from client side script. and you can not do that directly.
Instead you can call an ajax function which send an HTTP request to some script placed on server. And in that server script write the code to read the existing files in a directory and rename them using file handling operations.

Input to Javascript from file via php

I have a setup where I want to send the results of a python script asynchronously to a webpage. I currently have a HTML page setup, with a Javascript file that deals with the information dynamically.
However, I don't really understand how to get the Javascript to interact with Server-side files, seeing as its done through PHP. What do I do to set up a php file that takes the input from a text file (generated every x seconds from the python script), and sends it to the Javascript?
Probably the easiest way is to create iframe that will refresh every x seconds that points to that genereted file. Not sure if this will work in your situation.
<iframe id="genFile" src="link/to/genFile.txt"></iframe>
<script type = "text/javascript">
window.onload = function() {
setInterval(function () {
document.getElementById('genFile').contentWindow.location.reload(true);
}, 3000);
}
</script>
More complicated way is to use server side php script that will read that generated file content and setting up ajax requests to get script output every few seconds. This is better if you need to process this file between reading and outputting or when file is out of public scope.

Categories