Question

So, I'm developing a node.js app that will show some markers in google maps according to the locations it finds in the database, which will then be converted and saved to a .txt file. Everything works great up until that point. If i do a console.log() of the converted latitudes and longitudes it will show them perfectly. However, in the .html file with the maps api i have to import the file that will return the coordinates. Since this file is written in html with script tags to import the script, it interprets those scripts as javascript, and because of that, it stops working. Firebug shows me that the file is found and shows me the content of it, but in the .js script file i have to do stuff like this to use node.js modules, that are necessary for my functions to work.

var fs = require('node-fs');

or like this to use functions in the file from other modules.

exports.someFunction = someFunction;

So, when the browser loads the map and tries to find the coordinates that i'm passing from the script that reads the .txt file where they're saved, it finds any of those two things and can't process them, because they're node.js, not plain javascript.

So my question is, how do i get javascript to recognize require() and exports when they're node.js commands?

Was it helpful?

Solution

If I understand you correctly and you're trying to use Node.js module system in browsers, that won't work. Browsers doesn't implement such features natively. Script files can only be included to the page with script tags or some kind of ajax system that fetches the files from the server. There are few such a libraries that provide such a functionalities.

RequireJS might be what you're looking for the client side though.

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Also note that some of the Node.js features are not possible in the browsers. For example the direct file system access is not possible in the browsers, it would be a huge security risk. Most javascript modules that provide both server and client side functionalities explicitly mentions it and provide separate script files for both sides.

Also if you only want to send coordinate data from the server to the client, then it might be good to use Ajax or WebSocket to send the data in a JSON format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top