Javascript Write to File System - javascript

I need to write to the file system of my web application. Please don't respond "you can't do that" because it isn't helpful. I see that it can be done with HTML5, php, python, etc. I am just doing 1 basic write. The written file is crawled by a search engine, which is why I have this weird requirement.
To perform the file read I do something like this:
$.ajax({
type: "POST",
url: "./engine-text.txt",
dataType: "text",
async: false,
success: function (data) {
text_data = data;
}
});
I'd like to do something simple to write. I'm just adding or removing lines of text to this file and writing it back. As it stands I don't have php or python. I basically have JQuery, HTML5, and Ruby. Remember another program needs to be able to read this file, so I don't think HTML5 will work.
Thanks!

Generally you can't in your browser due to security concerns.
However it doesn't mean you can't get your browser to make your server to do it -> eg Server Side JavaScript Node.js.
eg using Filesystem
var fs = require('fs');
fs.writeFile("yourpath", "Hello", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
Some browsers do now allow File system access through the File Api:
https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API
see this link for a more detailed answer:
Local file access with javascript

Related

Are there security risks storing JavaScript files in localStorage as an offline version of the file?

I have an app that reads the contents of example.js using an AJAX call to example.php, then saves example.js to a variable, localStorage.exampleJS, every time the user opens the app on their phone.
The AJAX call uses the following jQuery:
$.ajax({
type: "POST",
url: "https://example.com/example.php",
success: function(response){
localStorage.exampleJS = response;
},
});
example.php contains the following:
<?php
echo file_get_contents('example.js');
?>
In the event that the the user doesn't have an internet connection, I run the offline version using the following jQuery:
if(navigator.onLine){
$("head").append("<script src='https://example.com/example.js'></script>");
}
else{
$("head").append("<script>" + localStorage.exampleJS + "</script>");
}
I know this could potentially have security risks. Is this a bad practice? Are there security risks doing saving an offline version this way? Is there a better way to do this? Thanks!
I think there is no harm storing file in local-storage, but have to keep following things in your mind.
File size should not be more than the local-storage size. at any point of time you could utilized full local-storage then you would not be able to store more file.
Ensure that your all files are uglify and minify, since it will help you in security and space optimization. As uglfy is not human readable so anyone try to read it he is not able to read as file is in uglify form, and minify helps to reduce the file size.

JS AJAX to post generated file as PDF to server directory

I have a complex table generated via javascript that I'd like to save as PDF on the server. I've looked around at the pdf generation libraries and they all seem to be limited in terms of style, fonts, etc (that's what I meant by 'complex'). The table can be download client side as PDF or printed.
Let's say my function that generates the form to be printed is reportBody(data); - is there a way I can use AJAX to send the document as PDF to a php file that will save it server-side instead of downloading it client-side? The reportBody(data) is a collection of other variables, function calls etc.
So basically the question is - since we can generate a PDF file client-side, can we POST it (the pdf) via ajax to the server?
Short answer is Yes. Your provided information is still limited as it's not clear what is ran in the reporBody(data) but most PDF libraries on client side are able to give you the PDF file as base64 encoded data in form of a string.
You can then simply send that string to the server and save that as a PDF file.
A simple implementation will be something like this:
// I have used jQuery for convenience but you can use any lib or Vanilla JS
var saveData = $.ajax({
type: 'POST',
url: "url-to-the-php-script",
data: { pdfData: 'base64StringDataHere'},
dataType: "JSON",
success: function(resultData) { alert("Save Complete") }
});
Then on server side, do something like this:
$pdfData= $_POST['pdfData'];
file_put_contents('filename.pdf', base64_decode($pdfData));
Yes, there are a lot of ways. One would be, if you have html code in your reportBody(data); you could:
Send the html to a php file via ajax
in this php you could use https://wkhtmltopdf.org/ to generate a pdf file
In the client side you could point to that pdf generated

checking files on client side

I'm developing a web site on ASP.Net/MVC 4
I write this code to check the files if they are exist, but I think it will work only on the server side , how can I do the same process on the client side ?
string path="c:\\Program Files";
string[] filesName = Directory.GetDirectories(Path);
for (int i = 0; i < filesName.Length; i++)
{
..............
.......
}
You cannot.
It would be a horrible security threat if any website a user visited could explore their hard disk to see what files it had on it.
That would reveal information about what software they used and whatever private information appeared in file names.
You can use AJAX & jquery to check if a file exists at particular path on your server.
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
Due to security reasons javascript can't directly access clients's file system. Maximum that yo can do is that you may have a browse button that allows user to browse and point to the file and then you can validate the file and perform the desired action. Otherwise try using java applets/flash.
Check Read a local file using JavaScript HTML5 file api (offline website)

Uploading XML file using AJAX

I've found a mound of questions on SO regarding uploading a file using AJAX although none of them really seem to find my needs.
What I need to do is have a user upload an XML file and have the script run through the XML file and take out the data that is in certain tags in the file and then push the data into a corresponding array which reflects the tag. So say I found a book in an xml, it would push the data into an array NewBooks.
I don't have any experience with PHP, quite honestly its confusing to me. If there is a way without PHP, that would be grand.
reader.onload = function (e) {
console.log('reading file')
$(document).ready(function () {
console.log('analyzing ajax')
$.ajax({
type: "GET",
dataType: "xml",
success: function (xml) {
$(xml).find('book').each(function () {
UploadBooks.push($(this).text());
});
}
})
})
console.log(UploadBooks);
}
That is the code I have although the printed UploadBooks has no elements, even though when I look into the XML file, there are clearly book tags.
Not all browsers can upload files via Ajax. Only those supporting XMLHttpRequest2. Getting that to work with jQuery (as per your example) is going to take some tricks too.
You say you'd rather not use PHP, which would mean no point uploading a file anyway. Check out the HTML5 FileReader API if you want to try and parse the XML file on the client side. You might be able to load the file into a DOM structure to achieve what you're trying to do.

Reading local XML file with javascript

I am new to HTML/Javascript, as well as coding in general so bear with me :). I am trying to create a "Spot the Difference" game in html5 using javascript. Everything is local (on my machine). I have two pictures, of the same size, one with differences. To generate data about the clickable fields, I have a java program that reads both of the images and outputs all of the positions in which pixels are different into a XML file. My plan was to then use this XML file with my javascript to define where the user could click. However, it appears (correct me if I'm wrong) that javascript cannot read local XML files for security reasons. I do not want to use an ActiveXObject because I plan on putting this onto mobile devices via phone gap or a webkit object. Does anyone have a better approach to this problem, or perhaps a way to read local XML files via javascript? Any help would be greatly appreciated, thanks.
If you are planning to put this into a smart phones (iOS and Android) and read local files, I have done similar things with JSON (yes, please don't use XML).
Convert your output to JSON
Put this as part of your application package. For example, in Android, I put it as part of the .apk in /appFiles/json
Create a custom content provider that would read the local file. I create mine as content:// but you create whatever scheme you want. You could leverage android.content.ContentProvider in order to achieve custom URL Scheme. iOS has its own way to create custom scheme as well. The implementation simply read your local storage and give the content
To read it from Javascript, I simply call ajax with the custom scheme to get the json file. For example content://myfile/theFile.json simply redirect me to particular directory in local storage with /myfile/theFile.json appended to it
Below is the sample to override openFile() in the ContentProvider
public ParcelFileDescriptor openFile (Uri uri, String mode) {
try {
Context c = getContext();
File cacheDir = c.getCacheDir();
String uriString = uri.toString();
String htmlFile = uriString.replaceAll(CUSTOM_CONTENT_URI, "");
// Translate the uri into pointer in the cache
File htmlResource = new File(cacheDir.toString() + File.separator + htmlFile);
File parentDir = htmlResource.getParentFile();
if(!parentDir.exists()) {
parentDir.mkdirs();
}
// get the file from one of the resources within the local storage
InputStream in = WebViewContentProvider.class.getResourceAsStream(htmlFile);
// copy the local storage to a cache file
copy(in, new FileOutputStream(htmlResource));
return ParcelFileDescriptor.open(htmlResource, ParcelFileDescriptor.MODE_READ_WRITE);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
I hope it helps
I would suggest modifying your java program to output a JSON formatted file instead of XML. JSON is native to JavaScript and will be much simpler for you to load.
As for actually loading the data, i'm not sure what the best option is as you say you want to evenutally run this on a mobile device. If you were just making a normal website you could setup a web server using either Apache or IIS depending on your OS and put the files in the document root. Once you've done that you can load the JSON file via Ajax, which can easily be googled for.
Not sure if this helps any.
Since this is a local file, you can do this with jQuery
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
success: function(xml){
///do your thing
}
});
http://api.jquery.com/jQuery.ajax/

Categories

Resources