1

I'm having some trouble with a basic thing in coffeescript. I'm trying to read a JSON file but it doesn't works. I'm getting a

ReferenceError: require is not defined

which points to this line

fs  = require ("fs")

My whole script is this (routes.js.coffee):

loadFiles = ->
  fs  = require "fs"
  fs.readFile 'A4.json', (err, geoData) -> fileText = geoData

ready = ->
  geoData = loadFiles() #Guess this line is wrong but I need to focus on the other error
  map = L.map('map').setView([5.81107293, -73.030279174], 13)

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?  access_token={accessToken}', {
attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
#Some irrelevant code...
}).addTo(map);

$(document).ready(ready)
$(document).on('page:load', ready)

I've been reading other related questions posted here but the suggested solutions haven't worked for me (order the imports). My application.js is this:

//= require jquery
//= require jquery_ujs
//= require leaflet
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

Thanks in advance

1 Answer 1

1

If you really want to use require at the client-side then you should consider to add require.js to use Require.js.

In this case specifically, it looks like that you're just trying to get some data in a json file dinamically. You could try somethiing like this:

ready = ->
  $.get "A4.json", (geoData)->
    fileText = geoData
    map = L.map('map').setView([5.81107293, -73.030279174], 13)
    # ...
5
  • I didn't know this was another option!, thanks for the suggestion, I'll use it instead... Are you sure this is the right code?, I'm getting a ReferenceError: geoData is not defined Dec 23, 2015 at 15:31
  • No, I'm not sure. This piece of code is focused on showing you how to use jquery's get method. This geoData is just the data returned from that file. If if says you that is not defined then maybe your indentation is not right. try to put it more two spaces right
    – Tofani
    Dec 23, 2015 at 15:35
  • In fact this geoData code, at least in your posted code, is not being used. Do you really need to read this data?
    – Tofani
    Dec 23, 2015 at 15:35
  • @user2782149 you look like to be new to stackoverflow. If this answer or any other one solved your issue, please don't forget to mark it as accepted :)
    – Tofani
    Dec 23, 2015 at 15:39
  • You were right, indentation problem. I do need that info, this was just a small test to read it from a file. Thanks again Dec 23, 2015 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.