Javascript - create text file on website - javascript

So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.
e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt
Is there a way to do this with HTML/Javascript?
EDIT:
I am on Github

You can't do it with HTML/Javascript alone, you need a functional language on the backend (nodejs, php, python)

You can use ActiveXObject, but it won't work in all browsers.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
https://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

If, when you say "JavaScript", you're referring to a node.js application running on a server, then this is possible. It doesn't have to be node though; it could be a Django site, or an ASP.Net site, doesn't matter. You can't have JS code in the browser create files on your server... the JS in the browser is executing on a client machine, and doesn't have access to the server's file system.
You could create an endpoint to which your clients could send requests that would initiate the creation of the file.
You could also allow clients to PUT or POST files to your server, but again, this is something you control from the server side of the application. Your webpage (i.e., HTML file as you put it) cannot create files on the server itself. Your server allows clients to send it files in a specific manner, and the client must adhere to those rules.

The short answer to your question is no.
The long answer is that you have the following alternatives:
Use a form on the Browser end, send the data back to the server, and then use a server-side language such as PHP to receive and save the data. No JavaScript required, but you do need server-side programming.
You can make the process more immediate by using JavaScript on the browser end to send data back to the server. This is called Ajax. You will still need server side processing, though.
Note that it is probably a very bad idea to simple accept user data and save it directly. There are two things you should consider in your development:
Always filter the incoming data against the possibility of receiving and accepting carefully crafted malicious data.
Consider storing the data in a database. Apart from being easier to manage (you don’t have to worry about filenames, for example), they can do less damage there.

You can achieve this in IE browser using the following code.
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
if you are looking for a goos reliable solution then better to use PHP and other server scripts.

Related

Is this client side application secure?

Here is a simplified version of a program I am using to work with a file using javascript on the client side.
HTML:
<input id='myinput' type='file' accept='.png, .jpg, .jpeg' />
Javascript:
var myinput = document.getElementById('myinput');
myinput.addEventListener('change', function(e) {
/* 1. capture the file */
var file = e.target.files[0];
/* 2. make a fileReader object */
var reader = new FileReader();
/* 3. the load event listener */
reader.addEventListener('load', function(e) {
var fileContentAsText = e.target.result; // <-- is this line safe?
/* 5. functions for manipulating the file would go here */
}, false);
/* 4. passing the file to the filereader object */
reader.readAsText(file);
});
More or less, my program is for manipulating png or jpg type files, manipulating them, then making the modified version available for download.
Everything happens on the client side.
Since nothing is being sent to the server, are there any security vulnerabilities that I should be concerned about?
If I was sending it to the server, almost everything I would have done to validate the file would have been in php, and I would have been reasonably assured that the operation was secure enough.
Since I am not sending it to the server, none of those php mechanisms I would have applied are applicable.
Actual questions:
Given that everything will happen on the client side, do I need to validate the file?
If so, why? And what actions can I take?
What comes to mind are text boxes that set the innerHTML of other elements, or where src/onerror attributes can be exploited for nefarious purposes. Are these types of attacks something I need to watch out for? Because everything I have read on this matter concerns validating a file that goes to the server.
You have to be aware of vulnerabilities like for example cross-site scripting, open redirection, sensitive information storage (not a comprehensive list), which may also affect client-only applications.
In practice this means the important part is point 5. in the comments - what happens to the loaded file. For example you could store part of it after processing in say localStorage, which may present a risk if "sensitive" info is stored (be it whatever in your context). Or for example if a part is written back to the client (which I think is the case if I understand correctly), it could pose an injection threat. The most straightforward injection would be XSS if you for example write somehing to html, like the comment from the image exif. But you should also consider what happens to the resulting file after the user receives the result. Will it be displayed in an application that may be vulnerable to some kind of an injection, or for example buffer overflow? Consider an image viewer that has a known buffer overflow vulnerability. Say a malicious user prepares an image and gives it to the victim. This image may be crafted in a way that it does not directly result in buffer overflow, but after the transformations your application does to it, it exploits vulnerabilities in the client that displays it. Sure, it's a vulnerability of the 3rd party client software, but your application was used to hide the exploit and facilitate an attack.
So try to consider the system as a whole, your apllication may just be a building block in a complex attack, and your goal should be to minimize the usefulness for an attacker. This is vague advice, but it all depends on what you actually do to the uploaded file.
Another thing that comes to mind is a malicious uploaded image may hang the browser process, a denial of service on the client. You should be able to avoid this. (Sure, the user uploads it for herself, but may not be aware of what it is she's uploading, having received it from somebody else - may or may not be valid in your scenario.)
Aldo during processing, parts of the image info may be used for say querying things, for example to find the camera vendor from the exif info or whatever. Such queries may also be susceptible to injection, resulting in query forgery via a malicious image. So anything you read from the file during processing should be treated as untrusted in general, the same as if it was done on the server.
Client side will never be safe. Even though you're using accept attribute in input type="file", it will only identify the open dialog to identify the given types and show them only. But user can still choose Select All option there and and select any type of file. And reader.readAsText(file); will read it as it is and will not validate. This means hacker can upload anything desired and can inject in the application. Thus, always consider making validation through server side language.
then making the modified version
This will not make any sense since application can upload anything rather than the specified file types.

HTML download counter without PHP

I'm wondering if it's possible to make a download counter without the use of php. I have been told it's possible but cannot find anywhere that has helped me.
I am trying to save the counts to text file on the server. I cannot use php as my server does not allow the use of it. I have tried javascript but can't seem to get anything working. Any suggestions or guidance would be appreciated!
The server allows, html, javascript, and css.
PHP is the most common server language available on hosting services, if your server does not allow it, it's possible you can't use any language at all on the server side.
Let's assume you can't use any language on the server side, then there is two possible actions.
use a third party server where you can save your data.
save locally your data using javascript.
Using a 3rd party service might be complex to implement and you need to learn a bit about cross origin request. You will need to add a few javascript librairies and understand a lots of concept so I'll just go with the easy one.
You browser have a localStorage wich can be access through Javascrip
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
[!] Know that this will be save only on your browser therefore other users or session will not have access to the counter.
// get the saved value or zero if not found
var count = localStorage.getItem('so-demo') || 0;
// increment the value by 1
count++;
// save the value
localStorage.setItem('so-demo', count);
// show the actual value
document.getElementById('theValue').innerHTML = count
<div id="theValue">localStorage is not allowed on stack overflow but works elsewhere</div>
The similar question had already been raised, check out this topic
The way suggested with Google Analytics out there is quite a good idea

Read/write json from js to file on server (not server app)

I'm working with a .js client and have and object that I need to write out to a file on the server. A couple of questions - file i/o with JavaScript is new to me... I was planning on using jquery and json. I'm using java serverside. I don't have a problem reading what I get back from my servlet, but the file i/o is killing me! A couple of questions:
I can open a file I generated myself via the .js with an $.ajax call, but it's not handling my json syntax (I tried both an $.getJson and $.ajax - handwritten json, so I might (probably) are doing something wrong with it). I used firebug's console and it looks ok...
How can I write my object to a file on the server?
Then, when I want to read it, what do I need to do to process it? Right now I'm using a jsonFilter function (uses JSON.parse if that's available, otherwise eval) to process data that I'm getting from the servlet.
The object I'm writing isn't simple, but it's not super complex either. There's an array that contains an array, but that shouldn't make a difference if the software is both reading/writing it.
Thanks for any help! I'm at a loss - tried alot of different things.
You can open a file located on the server via ajax by querying the file and loading it into a JSON object. You might want to LINT your JSON
You can not write to an object on the server via the client. This is a severe security breach.
Common practice is to change the JSON data and then send it via ajax to server-side code. The server will then do the file IO.
Yes using JSON.parse otherwise eval is indeed correct. I would recommend json2.js
The data should be fine as long as it passes JSONLint.
Your main issue is that it's impossible to write to the server from the client. Get the client to load the data through ajax change it and then query the server to update the file.
js don't have i/o property;
you should use ajax or http request to send message to server,and tell server to do de i/o action...

How to access a property file using "javascript"

How do I access a property file using javascript. Normally property file is a xml based file.
I java we access a property file like this:
Properties prop = new Properties();
fis = getClass().getResourceAsStream("props.xml");
if (fis != null) {
prop.loadFromXML(fis);
}
String dbUrl = prop.getProperty("dburl");
I want to do the same but using javascript. is there a possible way of doing it?.
JavaScript can't load files, as part of its security model. It can retrieve XML from the server using AJAX, but it can't read files from the client computer.
You can't load any files from the users computer with javascript in the browser.
If the file is from your own server you can load it, like any other ajax, with XMLHttpRequest.
Javascript doesn't use property files, as, either it has all the information it needs in the javascript files or in the html, or it will make an XMLHTTPRequest call to get the information from the server.
The server can look at the property file, and may use information passed in from the request, such as the header information, to know more about the client, to determine what information to pass back.
So, if you want to pass back some localized information, the server would have to get that from the browser request and then it could send back just what is needed for that transaction.
Javascript is different from java, so one limit is that javascript cannot read from the hard drive of the user, and since it is a webpage, the user wouldn't have the property file installed, it would still be on the server.
Javascript can only make requests to the address that that script came from, so there is a second sandbox rule that has to be met.
You may want to better understand javascript, then try to rephrase your question.
HTML5 now allows JavaScript to read local files, via the File API:
http://www.html5rocks.com/en/tutorials/file/dndfiles/

pyfacebook and javascript query

I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas?
You can't pass a variable directly, as JavaScript is running on the client (browser), and Python is running on the server.
You could make a XHR (AJAX) request from JavaScript to the server which would then return your values back to JS (JSON could be used here).
Or you could put a hidden field to your markup that would have the value in it's "value" attribute. You could then read that with JavaScript.
ps: your question really isn't related to pyfacebook but Python (or any other server side technology) in general and that has been covered here many many times.

Categories

Resources