How to Make Js Know About the Application Root

How do I make JS know about the application root?

If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use / as the first character of your url.

var urlToJobIndex2= "/jobs/GetIndex";

Here is an alternate approach if you want more than just the app root (Ex : Specific urls( built using mvc helper methods such as Url.RouteUrl etc)

You may use the Url.Content helper method in your razor view to generate the url to the app base, assign it to a javascript variable and use that in your other js code to build your other urls.
Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.

If you want to get url to a specific action method, you may use the Url.Action or Url.RouteUrl helper methods.

So in your razor view (Layout file or specific view), you may do this.

<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
myApp.Urls.jobIndexUrl= '@Url.Action("GetIndex","jobs")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>

And in your PageSpecificExternalJsFile.js file, you can read it like

var urlToJobIndex= myApp.Urls.jobIndexUrl;
// Or With the base url, you may safely add the remaining url route.
var urlToJobIndex2= myApp.Urls.baseUrl+"jobs/GetIndex";

Here is a detailed answer about the same , but using this in a specific page/view

Angular Js

You might need the correct relative url(s) in your angular controller / services / directives.The same approach will work for your angular code as well. Simply build the js namespace object and use the angular value provider to pass the data to your angular controllers/services/directives as explained in this post in detail with example code.

Determine project root from a running node.js application

There are many ways to approach this, each with their own pros and cons:

require.main.filename

From http://nodejs.org/api/modules.html:

When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing require.main === module

Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.

So if you want the base directory for your app, you can do:

const { dirname } = require('path');
const appDir = dirname(require.main.filename);

Pros & Cons

This will work great most of the time, but if you're running your app with a launcher like pm2 or running mocha tests, this method will fail. This also won't work when using Node.js ES modules, where require.main is not available.

module.paths

Node publishes all the module search paths to module.paths. We can traverse these and pick the first one that resolves.

async function getAppPath() {
const { dirname } = require('path');
const { constants, promises: { access } } = require('fs');

for (let path of module.paths) {
try {
await access(path, constants.F_OK);
return dirname(path);
} catch (e) {
// Just move on to next path
}
}
}

Pros & Cons

This will sometimes work, but is not reliable when used in a package because it may return the directory that the package is installed in rather than the directory that the application is installed in.

Using a global variable

Node has a global namespace object called global — anything that you attach to this object will be available everywhere in your app. So, in your index.js (or app.js or whatever your main app
file is named), you can just define a global variable:

// index.js
var path = require('path');
global.appRoot = path.resolve(__dirname);

// lib/moduleA/component1.js
require(appRoot + '/lib/moduleB/component2.js');

Pros & Cons

Works consistently, but you have to rely on a global variable, which means that you can't easily reuse components/etc.

process.cwd()

This returns the current working directory. Not reliable at all, as it's entirely dependent on what directory the process was launched from:

$ cd /home/demo/
$ mkdir subdir
$ echo "console.log(process.cwd());" > subdir/demo.js
$ node subdir/demo.js
/home/demo
$ cd subdir
$ node demo.js
/home/demo/subdir

app-root-path

To address this issue, I've created a node module called app-root-path. Usage is simple:

const appRoot = require('app-root-path');
const myModule = require(`${ appRoot }/lib/my-module.js`);

The app-root-path module uses several techniques to determine the root path of the app, taking into account globally installed modules (for example, if your app is running in /var/www/ but the module is installed in ~/.nvm/v0.x.x/lib/node/). It won't work 100% of the time, but it's going to work in most common scenarios.

Pros & Cons

Works without configuration in most circumstances. Also provides some nice additional convenience methods (see project page). The biggest con is that it won't work if:

  • You're using a launcher, like pm2
  • AND, the module isn't installed inside your app's node_modules directory (for example, if you installed it globally)

You can get around this by either setting a APP_ROOT_PATH environmental variable, or by calling .setPath() on the module, but in that case, you're probably better off using the global method.

NODE_PATH environmental variable

If you're looking for a way to determine the root path of the current app, one of the above solutions is likely to work best for you. If, on the other hand, you're trying to solve the problem of loading app modules reliably, I highly recommend looking into the NODE_PATH environmental variable.

Node's Modules system looks for modules in a variety of locations. One of these locations is wherever process.env.NODE_PATH points. If you set this environmental variable, then you can require modules with the standard module loader without any other changes.

For example, if you set NODE_PATH to /var/www/lib, the the following would work just fine:

require('module2/component.js');
// ^ looks for /var/www/lib/module2/component.js

A great way to do this is using npm:

{
"scripts": {
"start": "NODE_PATH=. node app.js"
}
}

Now you can start your app with npm start and you're golden. I combine this with my enforce-node-path module, which prevents accidentally loading the app without NODE_PATH set. For even more control over enforcing environmental variables, see checkenv.

One gotcha: NODE_PATH must be set outside of the node app. You cannot do something like process.env.NODE_PATH = path.resolve(__dirname) because the module loader caches the list of directories it will search before your app runs.

[added 4/6/16] Another really promising module that attempts to solve this problem is wavy.

App Root in Javascript

you can use

<% response.write "<script>var appRoot =  """ & Url.Content("~/AppRoot") & """</script>" %>

before calling the .js file in the dinamic part of your app (.aspx)

Get root path of application in javascript

Javascript can't know what's the the root path of your application.

But since you tagged your question with asp.net, you can use virtual paths and asp.net will handle the paths for you.

So instead of:

<sometag src="xyz.com/InnerDirectory/something.css">

Write this:

<sometag src="~/something.css">

Read more here.

BTW, if you use ASP.NET MVC, it's even easier as you should use the @Url.Content \ Url.Action helpers

How-to get the Application path using javascript

This will give you a result but would have to be modified if you have more levels (see commented code).

var path = location.pathname.split('/');
if (path[path.length-1].indexOf('.html')>-1) {
path.length = path.length - 1;
}
var app = path[path.length-2]; // if you just want 'three'
// var app = path.join('/'); // if you want the whole thing like '/one/two/three'
console.log(app);

Getting the website root in Javascript

Yes: window.location.hostname

How to create a root component for making a request regardless of page url in next.js?

You need to create _app.ts file in your pages directory. and add the following snippet.This component is the root component in next js and it any function you write here will be executed once depending on how you call this function.

for more info, check this link in Next Js docs https://nextjs.org/docs/advanced-features/custom-app

// import App from 'next/app'

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}

// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }

export default MyApp


Related Topics



Leave a reply



Submit