Reading from & writing to files in same domain using JavaScript - javascript

Say I have a website hosted via Bluehost or the like, at example.com. If I have a file stored at example.com/a.txt, how can I go about reading from this file? And, if I want to write a new string to this file, is it possible to do so, or is it impossible with JavaScript in the web?

you could make a simple api using express and use file-system or fs
with that package you can do that with a single line after doing const fs = require("fs"); :
const constant = fs.readFileSync("path"); //read the file
fs.writeFile("path", "something to write", () => {
//a callback func
});```

In short no. But you have workarounds:
You can open some folder for the public view:
static files - read only access (styles and javascript)
media files - read only access (pictures and other media)
some manually created url - to edit/create the file in the media folder

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/>

How to load a random file from a directory

I am trying to create a question bank on GitHub Pages.
I load a specific file using:
$(document).ready(function() {
var theQuestion = "./questionsBank/"+"question-4"+".html"; //path to load
$("#question").load(theQuestion); //loading the question
});
Now, there are many files in the questionsBank directory and I would like to have a script picking and loading a random one, but I don't know how to do in JS.
How do you retrieve all filenames in questionsBank directory?
I would like to do something like below but don't know how to read filenames in a directory into an array:
var questionFolder = './some directory';
var questionFiles = [];
questionFiles = readingFilesandPopulatingIntoArray(questionFolder); \\how to do this?
var folderSize = questionFiles.length ;
randomNumber = Math.floor(Math.random() * folderSize);
randomQuestion = questionFiles[randomNumber];
$("#question").load(randomQuestion);
As commented by #Lawrence Cherone, the only way of getting the contents of a remote directory is by having an index of it.
Of course Apache has it's own directory scanner, which if configured ok, can render an HTML page with its contents. Then you could fetch that index and loop over the file links in it.
But GitHub Pages does not generates such indexes, so you need to generate it by your own. To do so, you need to do it during the build/deploy process of your page (which we don't know). There, you can add a NodeJS script (or whatever other language you prefer to use, like a plain bash script) using, for example, node's fs dir.read() to get the files list in ./questionsBank/ directory and generating a file to save it somehow (for example, a JSON file containing an Array).
Finally, you can include it directly in your code during the build process by importing it somewhere, or fetching it as you'd fetch any other URL containing a JSON (or whatever other format you decided to use).

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);

How to serve files from express 4.0 public folder as formatted html and not files, based on extension? E.g. format JSON, show images

Hey so anytime I place something in the "public" dir of my express directory, it automatically has a link on my webpage that I like. For example, going to https://website.com/image.jpg will allow me to download an image, and https://website.com/object.json will allow me to download a JSON file, without me having to do anything aside from place these files in my public folder. This is super convenient since I have another script that could be making a bunch of different things that I won't want to specify by name on my server every time I change something.
What I would like to do is modify this serve command so that when I want to retrieve an image, instead of automatically downloading it, it displays it in the browser. This should be as simple as adding an <html> </html> around anything in the public folder that has the .png file ending. Likewise, I would like to stringify any JSON file so that it comes out in a readable format (JSON.stringify(object,null,2));
Basically, I would like to be able to just put something in my public folder and automatically be able to access it in a desirable way based on its file extension. In these two cases the "desirable" way is not downloading the file, but displaying it in-browser in a human-friendly format.
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.
app.use(express.static(path.join('.', 'public')));
Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.
var fs = require('fs');
app.use(function(req, res, next){
fileName = req.url.substring('https://website.com/'.length);
if(fs.existsSync('public/'+fileName){
if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})
As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'

How to load the contents of a local text file by name using Javascript and HTML 5?

Working in Chrome, loading a local html or JS file.
I found many examples of how to load a file that is selected using the Choose File input.
However, didn't figure out how to do it given a file name without using the Choose File input.
The Choose File input returns a File object.
How to create the File object without the Choose File input?
From the File API:
new File(
Array parts,
String filename,
BlobPropertyBag properties
);
But didn't figure out what the parts and properties would be.
Edit: Use case:
I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.
The file would be opened from the browser and lives on the local machine. There is no server.
The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.
If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem:
https://developer.chrome.com/apps/fileSystem
The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:
var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // somecontent
};
No file will be read or stored on the clients machine.
If you are talking about creating files in nodejs then you should take a look at fs.
For security reasons all browsers don't support predefined values on file fields so the answer is you can't.

Categories