Home > Enterprise >  Understanding how path works in Node
Understanding how path works in Node

Time:04-30

So I have developed a Node Api and on local the path works fine, but I want to move it now to a server online, and don't know how to address the path.

This is the path in local: const path = "/Users/username/Code/projectname/api/invoices"

And what I want to do is make it work also for online, also to make sure that the folder api is what is going to be uploaded, not the one with projectname as it contains the client folder and other folders, so only the api folder.

CodePudding user response:

use __dirname to get the path of the folder.

The __dirname in a node script returns the path of the folder where the current JavaScript file resides.

const path = `${__dirname}/api/invoices`

CodePudding user response:

You can use the __dirname variable.


For this, you first need to import path.

const nodePath = require("path");

Then, to get the path, you need to join the directory name and your custom path together.

const path = nodePath.join(__dirname, "/api/invoices");

This should correctly join the path together.

Note: Naming conventions changed to avoid naming conflicts.


In conclusion, you can use the __dirname variable!

  • Related