Creating a NEW file using JavaScript

Hi there, is there any way that I’m able to create a completely new HTML file using JavaScript?

Note that I want to create a new file as opposed to editing an existing file

I’ve tried using fs as seen here:

const fs = require('fs');

function __newPage() {
  const output = document.querySelector('#output');
  const input = document.querySelector('#input');
  let randstr = Math.random().toString(36).substring(8);
  
  var html = `<html><p>Test</p></html>`;
  var dir = `/${randstr}.html`
  fs.writeFile(`./test.html`, html, function (error) { 
    alert(`${error}`);
  });
  
}

However, no file is being created. Any ideas?

It seems you are trying to mix NodeJS with client side Javascript. Could you try doing this all in NodeJS?

I’m not quite sure I understand the difference between the two ~ other than JavaScript is mainly client side, and node.js is server side…

Hey Sycolyy, welcome to the forum!

If you were running this code in a frontend <script>, then you can’t use the require('fs') syntax, which is a Node thing.

Likewise if you’re running this in the backend then there is no document.

I think what you meant to do was run this from Node in the backend, but you should lose the document selectors. Then, as long as __newPage() is being called from an Express/Fastify route, then it should work?

Let us know how it goes!

I think you mean Express/Fastify or Hapi route :slight_smile:

Migrated from Express to Fastify and finally settled on Hapi.