Home > Back-end >  cant write to a text file with javascript. (Uncaught ReferenceError: require is not defined at HTMLB
cant write to a text file with javascript. (Uncaught ReferenceError: require is not defined at HTMLB

Time:10-21

im trying to make a js app that tells someone to log in and saves the email and password in a text file, after some googling it looks like js doesn't have access to system files so node is required.

so i searched how to do it, but i keep getting an error that says Uncaught ReferenceError: require is not defined at HTMLButtonElement

this is the JS code:

let email = document.querySelector(".txt");
let password = document.querySelector(".pass");
let log_btn = document.querySelector("button");

log_btn.addEventListener("click", () => {
    let mail = email.value;
    let pass = password.value;

    var fs = require('fs');

    let content = `email: ${mail}\n password: ${pass}`;

    fs.writeFile("info.txt", content, err => {
        if (err) {
            console.error(err);
            return;
        }
        console.log("file created");
    }); 

    window.location.href = "index2.html"
})

what is preventing this from working, is there something i should include or install or anything. hope someone has the answer, thanks in advance.

CodePudding user response:

NodeJS is not a thing for browsers, it's a console application (the one outputting white text in black window)

To work with HTML and NodeJS at once, you need to use a mix of NodeJS and Browser, like https://nwjs.io/ or https://www.electronjs.org/

Download NWJS, upzip it, and open the HTML file with nw.exe, then you'll get a browser where you can use require and use filesystem


If the thing you want is making a web page which connects to a server that saves the file that's another thing, see https://adevait.com/nodejs/build-a-crud-app-with-only-json-files for example

CodePudding user response:

1 - If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
2 - If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
3 - To store some information on the client side that is considerably small, you can go for cookies.
4 - Using the HTML5 API for Local Storage.
  • Related