0

Is it possible to add a file into the website's directory?

In other words, let's say I have a directory – as an example I'll call it "myWeb"– it has index.html and main.js.

In main.js, I want to add a new page to myWeb when I click a button, let's say secondindex.html (for now, I won't worry about overwriting the file when clicked again).

Is this possible? If not, are there other techniques, or is this too broad?

Guillaume
  • 586
  • 3
  • 21
Christian
  • 132
  • 1
  • 14
  • 4
    Not with just JavaScript, no. You'd need some sort of server-side component, and this'd typically be done with databases, not actual individual files. Take StackOverflow, for example - it'd be insecure if you could use JS to put a `.html` file on their servers, and it'd be silly for there to be a separate `.html` file for every question. Instead, they have a set of scripts and a database. – ceejayoz Jul 11 '17 at 02:08
  • Why not, if not.. You can simply follow this solution for insight: https://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript – Tolulope Owolabi Jul 11 '17 at 02:17
  • @tolulopeowolabi That will not create a file on a webserver. – ceejayoz Jul 11 '17 at 02:19
  • You can't use the server's file system (modify its structure) inside of the client that would be a huuuge security loophole. However you can do such thing via server-side programming (php, node only to name a few) – Vivick Jul 11 '17 at 02:28

1 Answers1

0

For security reasons, the client-side cannot directly write to the server-side as they're not connected with one another. If writing a file to the server is what you want, you'll need a backend server and some kind of API/script that you interact with and create files that way.

There are other ways that don't involved creating files, such as using a database or cloud solution like Firebase. However, there are perfectly valid reasons you might want to keep your site basic and write static files (speed being one of them) and not wanting to setup and maintain a database being another.

This can be done using the fs module in Node.js for example:

var fs = require('fs');

function generateHtml (req) {
  return '<!DOCTYPE html><html><header><title>My Page</title></header><body><p>A test page</p></body></html>';
}

var filename = '/path/to/secondindex.html';
var stream = fs.createWriteStream(filename);

stream.once('open', function(fd) {
  var html = generateHtml();

  stream.write(html);

  stream.end();
});

The above would be in a Javascript file server-side and then you would have some kind of server checking for a request (preferably this would be protected using a token or something) and creating the needed file.

The fs module in particular is flexible in that you can create files many different ways. The above uses streams and is great for when you're dealing with potentially massive files.

Dwayne Charrington
  • 6,524
  • 7
  • 41
  • 63