Node JS fs module inside browser

I have a scenario in which I want to export data to CSV from the client side. I will have a text box / area or anywhere where the user can enter data, and then ideally with one click, the local CSV file will be updated with that data.

This is easily achieved using NodeJS with interaction with the server and its main modules (in particular, the fs module), but, apparently, not so much from the browser.

I found that some node modules (e.g. underscore ) support the RequireJS method to create a specific module in the browser. So for underlining, I did this:

methods.js

 define(['underscore'],function(_) { var Methods = { doSomething: function() { var x = _.size({one: 1, two: 2, three: 3, xuz: 3}); alert(x); } }; return Methods; }); 

common.js

 requirejs.config({ baseURL: 'node_modules', paths: { underscore: 'underscore/underscore', } }); require(['methods'], function(y){ y.doSomething(); }); 

index.html

 <script data-main="common" src="require.js"></script> <script> require(['common'], function() { require(['methods.js']); }); </script> 

The above works fine and will show a warning: 4.

But when I try the same with the fs module, it will not work. He will show this error:

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

As far as I understand, this is because fs requires several other modules, one of which is util .

So, I continued to add all of these modules to the RequireJS configuration. But I still had no luck, so I specifically tested the util module on its own, as this does not require other modules to work.

And now I'm stuck with this error: Uncaught ReferenceError: exports is not defined

I tried modulating this util module by encapsulating the entire source code of the module as follows:

 define([], function() {}) 

But that didn't work either ... I also tried to copy the underscore model, but still no luck.

Therefore, I was interested to know if anyone was able to use the util and fs modules (or any other NodeJS kernel modules) in a browser with libraries such as RequireJS or Browserify.

+6
source share
2 answers

That's right, exports is a node-specific JS (used to access the module outside the module) and is not supported by web browsers. Although NodeJS is technically JS, there are client-specific properties (for example, the window property for browsers and exports for NodeJS applications) that cannot be interchangeable.

However, here is the client-side JS response to the CSV issue.

+3
source

It is best (and probably only one) to use the HTML5 FileSystem API . I do not know of any other browser function that will allow working with files on the client computer, with the possible exception of Flash and a similar solution.

I am a little confused by your browser tag, since you are not explicitly using Browserify. This will fix your problem because "export is not defined".

+1
source

Source: https://habr.com/ru/post/978402/


All Articles