I am writing JavaScript code which is executed in a local web server. Is it possible to have that code generate another file, which is then added to the same directory as the original file? If so, how?
-
Please be more precise. Are you running the code clientside or serverside? – Chris Satchell Jun 23 '17 at 21:34
-
NodeJS is technically javascript and server side – dotKn0ck Jun 23 '17 at 21:42
2 Answers
I am not an expert on this, but I will try to help out. From my understanding the only way to create a file on the server is to have server side code do it. You could have the javascript call some endpoint and that could create the file. But I believe it is impossible to directly create the file.

- 355
- 2
- 15
-
What would an implementation of this look like? Sorry, I am new to web-based programming – user2593758 Jun 23 '17 at 21:51
-
I think a good place to start would be with Node.js. If you already know javascript you aren't learning a new language. There is definitely a learning curve though. I got started with [this](https://www.w3schools.com/nodejs/). – Alex Bieg Jun 23 '17 at 22:37
-
The structure would be: client->http.post->saves the file->returns to client a confirmation. – Alex Bieg Jun 23 '17 at 22:38
Things have greatly changed with HTML5 and so the answer is "Yes!" provided that one is using a modern browser and/or one takes advantage of JavaScript libraries that may aid with this endeavor. Take a look here as well as here. If you alter your browser's download settings to the desired folder of your local web server, when you submit the form the file will be downloaded there. I tried this using google chrome 49 on a windows box using wampserver and the file was saved exactly in the specified folder. After forking the code here, it ran successfully on my local webserver from the directory where I wanted the new file to be downloaded.
The pertinent jQuery code from codepen.io:
$("#btn-save").click( function() {
var text = $("#textarea").val();
var filename = $("#input-fileName").val()
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
});

- 3,797
- 2
- 27
- 33
-
This doesn't save file in same directory as current file. You have to change browser settings. – Ali Rehman Sep 05 '21 at 22:23