Saving .json file using javascript - javascript

I want to save json file to my application's directory using javascript. how to do it? my code only opens a new tab when you click download button and display the content of my json file. I am allowed to use client-side scripting only. I've tried this code but not working.
NOT WORKING CODE:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("location", true);
s.WriteLine(json);
s.Close();
Here's my code..
HTML CODE:
<!doctype html>
<html manifest="survey.manifest">
<head>
<title>Offline Survey Application</title>
<link rel="stylesheet" href="styles/survey.css" type="text/css">
<script type="text/javascript" src="scripts/survey.js"></script>
</head>
<body>
</body>
</html>
Javascript code
window.onload=function myFunction()
{
var btn=document.createElement("BUTTON");
btn.setAttribute('id', 'dButton');
btn.setAttribute('value', 'download');
var t=document.createTextNode("DOWNLOAD");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick=function clickedFunction(){
var url = "http://localhost/JSONFiles/survey.json";
window.open(url, 'download');
}
};
thanks in advance friends! :)

What you are trying to do would kill a lot of kittens.
For safety reasons, a web page cannot use activeX objects on a whim, nor access the local computer resources like file system in any way except what is allowed by standard (basically the cookies and local storage files).
That would allow any Russian hacker and his rabid dog to wreak havoc on computers all over the planet.
You can, however, try to use local storage if your json files are not too bulky and you don't expect to reuse them from another application.
If you plan on downloading json files, just point to them (i.e. put a link to whatever .json file somewhere on your page) and when the user clicks on such a link the browser will pop a save requester to let the user free to save the files in a location of his/her choosing.

If all you're trying to do is get a file on your server to download automatically instead of be viewed in the browser, you just need to set the Content-Disposition header the file is sent to the client with to "attachment". The easiest way to do that is to modify the config files for whatever server your using to add a rule for files of type .json. The exact methodology will differ depending on your server, though.

Related

Write file to dropbox via cronjob.de

I need to run code in javascript at specific time of a day. And every time when this script is triggered i need to save a file with some information.
So i figured out i'm gona use dropbox API to do that.
I have created new app in my dropbox account and generated token for it.
For test MY_SCRIPT.js looks like this:
var client = new Dropbox.Client({ token: "GENERATED_TOKEN" });
client.writeFile("FILE_NAME","DATA");
I have html file on the server (which i don't have access) with a structure like this:
<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/dropbox.js/0.10.2/dropbox.min.js"></script>
</head>
<body>
<script language="javascript" src="//PATH/MY_SCRIPT.js"> </script>
</body>
</html>
When i run this html file on my web browser it works fine (new file in dropbox app folder is being created).
But when i put this html address in new cronjob (cronjob.de) new files are not being created. Why? I assume the problem is access to the dropbox API from cronjob server. But how i can handle this?
The problem is that cronjob.deuses an browser / command that won't evaluate javascript. (such as curl)
So your javascript code will never be executed.
You should rather use an backend such as phpto run tasks of this kind.

running .bat file with javascript on html

I need to run a .bat file when the user clicks a link on the webpage. The .bat file basically runs another executable file and saves its output in a text file. So what I want is to create that text file once the user clicks the link to the .bat file on the webpage. Now, my .bat file is working perfectly when I execute it separately it creates the text file with contents, but somehow when I click the link it creates an empty text file. I looked at all the paths, they are all good;
I am using
Batch File ,
I have also tried
function runApp(which)
{ WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run (which,1,true);
}
But both of them just create the text file, and not put the contents
Does any one has any idea about this, also is there any other way to do this, like running the original .bat file and then getting its output in a text file directly with html/javascript?
Appriciate any help
Thanks
You don't say anything about what environment you are working with and I would guess you're not working with a server-side environment. JavaScript normally works in a browser to respond to the user's clicks and mouse moves etc but strictly within the confines of the browser. What you are trying to do is perform I/O operations on the underlying OS that the browser is running in (if you are running locally) or on the server-side OS in a normal webpage environment. It's not just a security issue - JavaScript simply doesn't have any direct connection to the client's OS or the server-side OS for that matter.
What you need is a web server environment like Apache or IIS etc, probably running an environment like ASP.NET, JSP, PHP(with a nice framework like CodeIgniter), or, rather you than me, CGI.
The user clicks a link or a submit button, and sends a request to the server. The relevant server-side program processes the request, runs the I/O operation you talk about and responds with the text. JavaScript is irrelevant in most of that process. It only comes into its own again when you are trying to figure out how to display the response in some fancy dynamic way.
There are millions of tutorials out there:
Tomcat (Java) http://wiki.apache.org/tomcat/GettingStarted
.NET(C# or VB) http://www.asp.net/get-started
Codeigniter (PHP) http://codeigniter.com/
CGI (not for the faint-hearted) http://www.cgi101.com/book/ch1/text.html
Having said all that, there is a server-side JavaScript environment (http://nodejs.org/) but the point is you will always be restricted by the limitations of the http protocol which means that you send a request to a server, the server processes your request depending on your privileges as a client, performing an I/O operation if appropriate, and responds with a stream of HTML. It does not allow direct operations on the server.
None of this is easy. Expect steep learning curves.
Displaying the text file contents
Here's a sample JSP page which will read the contents of a text file then display it on the webpage. I haven't added any buttons or anything - it just demonstrates how to read a file on the server:
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.io.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BufferedReader</title>
</head>
<body>
<%
String path = this.getServletContext().getRealPath("/target/message.txt");
File file = new File(path);
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
while(br.ready()){
out.print(br.readLine() + "<BR>");
}
reader.close();
%>
</body>
</html>
/target/message.txt is the virtual absolute path (from the root of the webapp). The call to getRealPath is the way you get a real physical path that allows you to create a File object.
I'll have a look later at using exec to run a batch file, but now you're thinking of a powerful language/library like Java why do you want to run a batch file? Wouldn't it make sense to write the program in Java?
use child_process.spawn of node.js

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

How do I open a file stream in javascript?

To give a concrete example of what I mean:
Imagine I have an HTML page that looks like this
<div>
<div id="filecontents">
<!-- some html file contents -->
</div>
<input type="button" />
</div>
I would like to be able to click on the button, and it bring me up with a "Open or save file" dialog box.
Is this even possible?
The objective of this is, is for me to be able to open up some html, text, or a CSV using the contents of a div as a data source for the file.
You can do this using the HTML5 FileSystem APIs. A couple tutorials here:
Reading local files in JavaScript
Exploring the FileSystem APIs
Browser support is weak right now, but my guess is that it's the closest to what you want.
doesn't <input type="file" /> do that exact thing?
I don't understand all these answers that say this is not possible without a plugin. I would say it absolutely is possible with standard web technologies, but requires user interaction and server interaction. Of course you can't go reading or writing whatever you want on a user's computer from the web, but you can ask a user for a file (open), and give a user a file (save).
To open a file with JavaScript, use a <input type="file" />. If you want, you can use JavaScript to display the open dialog by calling the click() method on the file input (the DOM method, not the jQuery method). In the onchange handler, submit the form, read the uploaded file, and write the contents to your page.
To save a file with JavaScript, send the contents of the file to the server, prepare the file, and stream it back to the client with a content-disposition header of attachment; filename="file.txt". This header causes the file to be downloaded and saved the user's pc rather than displayed in the browser.
Do that and you've officially written your first cloud computing app!
<input type="file" /> will allow you to upload a file to the server, but you have no direct access to that file, or to the local file system, from javascript - this is a security feature.
If you want to alter the page somehow based on the contents of the file, you will have to do a round-trip: upload the file to the server, then render a new page with the changes you want, and send it back to the client.
I have seen some file-stream-like code written for javascript (i.e., a flash implementation), but they must "load" files via an ajax request and then read the data as a javascript string.
You cannot access the local filesystem from javascript because of security reasons. You can, however, receive files via drag and drop in modern browsers or use an java applet that communicates with your javascript.
EDIT: forgot about the new HTML5 file api linked by Michael Mior. Go with his answer, he's the man. If you need cross browser support, go with the java applet, its painful but works.
Not with pure JavaScript. You can't open a file dialog to save part of the HTML, for example. Even if you could, there is no way to open a local file with JavaScript for security reasons (otherwise, malicious web sites could steal all your data).
But every browser allows to write plugins (most of them are written in JavaScript), so you could try this approach.
Use this script and put it in the button that the file browser should display.
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '"
title = "', escape(theFile.name), '" / > '].join('
');
document.getElementById('list').insertBefore(span, null);
};
})(f); reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

Access Local Files with Local Javascript [duplicate]

This question already has answers here:
Local file access with JavaScript
(14 answers)
Closed 8 years ago.
Based on the other answers on this site, I already feel like I know the answer to this question, but, as it's slightly different, I wanted to ask.
Is it possible to access local files from JavaScript that is running locally on the machine (AKA, my website address will be file:///C:/...)? Or, is this sandboxed as well?
What I am trying to do: I have a standalone computer that I want people to be able to drop in JSON or XML files into a local folder which are read in at the creation of the site and used to generate a single web page. If the JavaScript solution is not possible, can you provide any other suggestions?
Thank you.
A webpage can read any file on the same server as it was loaded from (this is the cross-site policy of JavaScript). That means that the page file:///C:/mywebsite/index.html can read the file file://C:/somedir/somefile.xml. To read this file, either use ajax, load it in an iFrame or load it as a javascript or css file.
Several browsers support custom methods for loading local file (and other interesting things), IE has activeX and Firefox has XPCOM.
According to the Firefox documentation, the following code will work:
var req = new XMLHttpRequest();
req.open('GET', 'file:///home/user/file.json', false);
req.send(null);
if(req.status == 0)
dump(req.responseText);
I seem to recall it only works within the same directory as the HTML page. And I don't know if this will work in other browsers.
This will only work on IE, but if that is not a problem for you, here is some sample code to write to a file:
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("c:\\path\\to\\myfile.txt" , 8, 1, -2);
s.writeline("Hello World");
s.Close();
And then to read from it:
f = fso.OpenTextFile(filename, ForReading);
while (!f.AtEndOfStream) {
var r = f.ReadLine();
document.write (r + "<br />");
}
f.Close();
For more information about OpenTextFile, check out: http://msdn.microsoft.com/en-us/library/314cz14s(VS.85).aspx
IF the user grants your webpage permission to access those files, and IF they are located on the same machine as the webpage, then there is nothing preventing you from gaining Read Only access to files on the machine via JavaScript.
If people are to drop a json string in to a folder, you could just have it be a plain text file, then use an AJAX call to the file name, just like you would point it to a php/asp script. I do this all the time for testing of pages before I have the backend done.
I.E. if your page were C:\foo\index.html, you could have them drop to C:\foo\putyourstuff\json.txt here and run an AJAX call "putyourstuffhere/json.txt".
You could read the files using just an Ajax request, as though it was to the server. But you have to know the name of the file, and you can't write files.
If you make an hypertext application page (.hta) instead of an HTML page (.htm/.html), then you have full access to the file system, using the FileSystemObject object.
(Well, limited by the file access of the user account that is running the browser, of course.)
This worked for me in Firefox...
Adapted code from this site: http://www.h-online.com/security/services/Firefox-Mozilla-Demo-Reading-local-files-via-local-HTML-files-761851.html
<HTML>
<BODY onLoad="ReadFileContent()" >
<iframe id="local_file" name="local_file"
src="file:///C:/test.txt"
height=0 width=0>
</iframe>
<script>
function ReadFileContent(){
alert(local_file.document.firstChild.innerHTML);
}
</script>
<h2>Read Local File</h2>
<P>
If a window displays the content of your local file C:\test.txt
the demo worked. If no additional window appears, it failed. You can
close this window now.</p>
</body>
</html>
You should consider some sort of server side scripting language such a PHP, Perl, JSP or some form of SSJS.
Yes, although insecure, you can use:
fopen("c:\\MyFile.txt", 'r');

Categories