Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.csv unable to go up one directory

I am trying to reference a file located in the parent folder using d3.csv and I am not able to find the correct syntax.

My folder structure is as follows:

root
└── js
    ├── data.csv
    └── myGraph.js

Inside the js folder I have myGraph.js. In this file I have the following piece of code:

d3.csv("data.csv", function(error, data) {
   data.forEach(function(d) {
   d.date = parseDate(d.date);
   d.close = +d.close;
});

If I place my data.csv inside the js folder everything works fine. However, if I move the data.csv file up in the root folder

root
├── data.csv
└── js       
    └── myGraph.js

and change the code to this then it stops working:

d3.csv("/../data.csv", function(error, data)

I have also tried:

d3.csv("../data.csv", function(error, data)

Does anyone know what I am doing wrong and what the correct syntax is? Many thanks.

like image 849
Robert Cazaciuc Avatar asked Jan 11 '17 10:01

Robert Cazaciuc


1 Answers

Robert - There are a couple of things to work through to get this to work:

1) Due to browser security models, you cannot directly reference/load files on your local machine from the browser by directly specifying either an absolute or relative path to files in your local directories. You have to use a local webserver to serve up your files and make them accessible to the browser (or you upload them somewhere where you have a URL which you can specify in the d3.csv call... but that would be tedious).

2) Usually, you can run basic HTTP servers in the directory that contains your .js and .html files. For example, if you have Python 3 installed system wide, you can start an HTTP server in a directory from the commandline using python -m http.server. Then you can access your site at http://localhost:8000 Unfortunately, this basic server only serves files within the directory it is launched in and doesn't allow for relative path references to other files outside the directory it was launched in. To achieve this, you would need to run a more capable/flexible local webserver that can be setup to allow relative path based referencing of files across a bunch of folders.

It is a bit tedious, but it makes sense why browsers are designed to not allow direct access to local files.

like image 75
HamsterHuey Avatar answered Nov 15 '22 16:11

HamsterHuey