I have a scenario where I want to export data to CSV from the client-side. I will have a textbox/area or whatever where the user can input data and then ideally with one click, a local CSV file will be updated with that data.
This is easily achievable with NodeJS with server interaction, and its core modules (specifically fs
module), but apparently not so much from a browser.
I found out that certain node modules (for example underscore
), support RequireJS's method of making a particular module work in the browser. So for underscore 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 an alert: 4.
But when I try the same with the fs
module it won't work. It will show this error:
Module name "util" has not been loaded yet for context: _. Use require([])
As far as I can understand, this is because fs
requires several other modules, one of them being util
.
So I proceeded to add all these modules to the RequireJS config. But still no luck, so I specifically tested util
module by itself as this doesn't seem to require other modules to work.
And now I am stuck on this error: Uncaught ReferenceError: exports is not defined
I tried modularizing this util
module by encapsulating the whole module source code in this:
define([], function() {})
But it didn't work either... I've also tried copying underscore
's model but still no luck.
So I was wondering if anyone managed to use util
& fs
modules (or any other core NodeJS modules) within the browser with libraries such as RequireJS or Browserify.
See Question&Answers more detail:
os