Module name "fs" has not been loaded yet for context error in NodeJs

user5799177 picture user5799177 · Aug 10, 2016 · Viewed 13.2k times · Source

I have been trying to use sql.js with NodeJs using WebStorm. I configured the NodeJs in WebStorm and tried running this code.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Database Test</title>
    <script src="js/require.js"></script>
    <script src="js/sql.js"></script>
</head>
<body>
<script>
    var fs = require('fs');
    var sql = window.SQL;
    var db = new sql.Database();
    sqlstr = "CREATE TABLE hello (a int, b char);";
    sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
    sqlstr += "INSERT INTO hello VALUES (1, 'world');"
    db.run(sqlstr);
    var res = db.exec("SELECT * FROM hello");
    var stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");
    var result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'});
    console.log(result);
    stmt.bind([0, 'hello']);
    while (stmt.step()) console.log(stmt.get());
    function add(a, b) {return a+b;}
    db.create_function("add_js", add);
    db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));");
    stmt.free();
    var binaryArray = db.export();
    var buffer = new Buffer(binaryArray);
    fs.writeFileSync("filename.sqlite", buffer);
</script>
</body>
</html>

but the code gives me an error in the console as

Uncaught Error: Module name "fs" has not been loaded yet for context: _. Use require([])

How do I resolve that error and run this complete code successfully?

Answer

alex picture alex · Aug 10, 2016

As far as I know you can't use fs on the front end to write files. But you can store variables in local storage on the front end if that is what you are trying to do?

Set the data in localStorage can be done with the command:

localStorage.setItem('nameForData', variableNameForData);

To retrieve the data when required.

var variableNameForData = localStorage.getItem('nameForData')

To remove the data from localStorage:

localStorage.removeItem('nameForData')

Docs for local storage here.

edit to answer comment

fs is used to access the file system in node on the local machine the code is running. With the command:

var fs = require('fs');

You are loading a included module that comes as part of Node.JS

This will not work in the browser for security reasons.

There are docs here that explain how fs works.

As I suggested, if you do want to store data on the front end, local storage is one way of doing so.