Relative Paths in JavaScript in an External File

Relative Paths in Javascript in an external file

JavaScript file paths

When in script, paths are relative to displayed page

to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:

Solution, which was employed on StackOverflow around Feb 2010:

<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>

If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section

relative path in javascript external file

An alternative solution is to apply classes to your elements via JavaScript and set a background image using CSS.

Relative url paths in CSS are always relative to the stylesheet file which can make them easier to keep consistent.

For example

Javascript

$.blockUI.defaults.message = '<div class="blockUI-Loader"></div>';

CSS

.blockUI-Loader {
/* url path is relative to this CSS file in "_assets/css" */
background-image: url(../images/blockUI_Loader.gif);
background-repeat: no-repeat;
width: nnpx; /* width of image */
height: nnpx; /* height of image */
}

relative path to images in external js script

I chose to put the file path information in the css file (set the image as the background of the link).
This way the js-script is independent of the image's file path.

Relative paths with fetch in Javascript

When you say fetch('data.json') you are effectively requesting http://yourdomain.com/data.json since it is relative to the page you're are making the request from. You should lead with forward slash, which will indicate that the path is relative to the domain root: fetch('/js/data.json'). Or fully qualify with your domain fetch('http://yourdomain.com/js/data.json').

NodeJS accessing file with relative path

You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');
var path = require('path');

var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.



Related Topics



Leave a reply



Submit