Home > database >  Making a folder with html and node.js
Making a folder with html and node.js

Time:06-03

I wanted to make a website that takes an input and, using node.js for the backend, makes a folder using mkdirSync(input.value). I have the fs module installed locally and I got it to work when using javascript only, but when I try to make it from a button on a web page it doesn't work. This is my folder and file structure:

  • Project folder
    • node_modules
    • src
      • index.html
      • script.js
    • package-lock.json
    • package.json

This is the code in the index.html and script.js files:

const fs = require("fs")
const btn = document.querySelector("#btn")
const input = document.querySelector("#in")
btn.addEventListener("click", () => {
    fs.mkdirSync(`./src/${input.value}`)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Document </title>
</head>
<body>
    <input type="text" id="in">
    <input type="submit" id="btn">

    <script src="script.js"></script>
</body>
</html>

Is it possible to do this in the first place? I cannot use PHP since I won't be able to use a server for this project. If you have ANY other ideas please tell me, it might be of help.

CodePudding user response:

You're misunderstanding how a backend works:

The backend is NOT a script attached to the HTML document So, your script.js won't work because it isn't backend code, its frontend code.

You can use Express.js to make your backend.

CodePudding user response:

You are mixing two concepts here that don't belong together. I will try to explain this using your first script:

const fs = require("fs");

This line belongs in a nodeJS context and has no idea what browsers, windows or documents are. Even if it knew it would still not work because browsers support ESM syntax, i.e. import but not CommonJs' require.

const btn = document.querySelector("#btn")
const input = document.querySelector("#in")
btn.addEventListener("click", () => {
    fs.mkdirSync(`./src/${input.value}`)
})

Here we are in a browser context. Browsers know nothing about file systems so all they can do is throw an error when they across something like fs.

You will need some sort of server/client architecture, I'm afraid, even when it's only a tiny local server.

  • Related