3

I am new but I have a function to write into a file JSON. But I want to write into a file. But require is not defined. So I use requirejs to be able to use fs so I can write file from a javascript function which would call that function. But I cannot understand how to "import" fs from node with requirejs, and even if it's possible to use fs with requirejs. Please help me if you can. Thank you a lot.

I tried to configure like on the site of requireJs for module of Node like that:

var requirejs = require('requirejs');
requirejs.config({
 nodeRequire : require
 });
requirejs(['fs'],
function (fs)
{
});

At the beginning, I have put my function into the function "function (fs) " but no result...

Here is my function js I want to use. She write into a json file after clicking on a button on BabylonJS for a virtual tour, a scene construction.

const fs = require('fs');
var obj = {
     story: []
     }
obj.story.push(
{"name": "infoHotspot",
    "type": "info",
    "position": (0,1,1)    
 })

var json = JSON.stringify(obj);


fs.writeFile('myjsonfile.json', json, 'utf8', function (err) {
    if (err) console.error(err)
});
Mathieu
  • 31
  • 2
  • if you're trying to do this from the browser, then you won't be able to do it with the fs module. instead, look into using iframes or a tags, like the answer here: https://stackoverflow.com/a/23013574/8003721 – Andrew Ault Jun 17 '19 at 12:55
  • What you try to do is not really clear, do you try to use a nodeJs module on a HTML page served by a server running with nodeJs? If so, be aware that nodeJs doesn't run in your page, but on the server. On which side do you want to write the file, on the client's computer? on the server? – Kaddath Jun 17 '19 at 12:57
  • I want to create my scene. So I create "hotspots" with picture etc.. After having finished my scene, I want to press a button GUI (from BabylonJS). This button have a trigger PickUp. Then after press this button, I would like to write into a json file which is in the same file that the html page. But I know that nodeJs is on server.side but I read somewhere that requireJs could replace it. More clear? – Mathieu Jun 17 '19 at 16:06
  • Actually you can't this way, requireJs can be used to import node modules in regular js, you are right, but the browser doesn't have the same access to the file system that nodeJs have, for security reasons. Your alternatives are to write the file server-side with fs and link it for download, or build the content in js client-side to simulate a download, with something like FileSaver.js for example – Kaddath Jun 18 '19 at 07:42

0 Answers0