Javascript path from root

Obtaining the Root Folder Path in Node.js using JavaScript

If the package binary is executed through an NPM script, the current working directory will be set to the project root, allowing for it to be required. These two approaches can be combined, which is often done to provide default locations for configuration files to third-party CLIs (such as Mocha). To ensure independence from installation methods or potential changes to NPM in the future, the location of the config file needs to be passed in through various methods. One way to do this is by setting the current working directory to the project root, which allows for access to the config file using the designated method.

Get the caller’s directory root from a node.js package

Are you satisfied with the result? By using __dirname , the function will always have the accurate location of file.yaml , regardless of where it is called.

const fs = require('fs'); exports.test = function(fileLocation) < // How should I *dynamically* reference the caller's app root directory? console.log(fs.readFileSync(fileLocation), 'utf8')); >
// Calling location test(path.join(__dirname, './file.yaml') 

Get parent directory name in Node.js, var path = require(‘path’); var parentDir = path.dirname(filename);. But it returns ../test1/folder1/FolderIWant . node.js

Accessing root public directory nodejs

An effective method to access your application’s root path from anywhere in the application without using relative paths is by utilizing the app-root-path module.

var appRoot = require('app-root-path'); router.get('/', function(req, res) < res.sendFile('index.html', < root: path.join(__dirname, appRoot + '/public') >); >); 

How to get the root path of node.js app Code Example, More “Kinda” Related Answers View All Javascript Answers » · nodejs create folder if not exist · node js create folder · node get all files in folder · listing dir

How do I require something in root project directory from inside node package library?

The binary package has the ability to receive the configuration path as an argument.

A binary package that cannot be executed as an NPM script should not be dependent on the structure of the parent project.

In case the NPM script is used to execute the package binary.

The set current working directory will be directed to the project root and can then be requested in the following way:

const config = require(path.join(process.cwd(), 'config')); 

A common practice involves the amalgamation of these two methods, which can furnish third-party CLI (such as Mocha) with pre-defined paths for configuration files.

If you’re currently situated in index.js and config.js exists in the directory above node_modules in your diagram, you can construct a pathway to config.js in this manner:

const path = require('path'); let configFilename = path.join(__dirname, "../../../", "config.js"); 

The directory where index.js is located is __dirname .

Ascend to the library_name directory using the initial ../ .

The next ../ will lead you to the directory located at node_modules .

Читайте также:  Add link php links

The third ../ leads to the project root, which is the parent of node_modules , and where config.js is located.

To ensure your module’s independence from installation methods or potential future changes to NPM, it’s necessary to pass the configuration file location through various means.

  1. To access the config file, set the project root as the current working directory and utilize process.cwd() .
  2. At the beginning of your project, you can establish the root directory by defining an environment variable.
  3. A module constructor function can be given the root directory as a parameter to enable its functionality.
  4. One way to pass the config object to a module constructor function is by loading and handing over the object directly.

I create module same your module.

When I refer to const config = require(‘../config’) , it performs its function successfully.

Get the caller’s directory root from a node.js package, I want x.test(); to output the contents of project/file.yaml , somehow dynamically referencing the caller’s root directory. javascript.

Node.js: Get (absolute) root path of installed npm package

require.resolve('bootstrap-sass/package.json') 
path_to_my_project/node_modules/bootstrap-sass/package.json 

It is now possible to eliminate the suffix «package.json» from the path.

var path = require('path') // npm install path var bootstrapPath = path.dirname(require.resolve('bootstrap-sass/package.json')) 

As every package must include the package.json file, it is expected to function at all times (refer to What is a package?).

There is no requirement for you to search for the package.json file of the desired package or mention its location directly.

It’s important to avoid doing it because there’s no guarantee where the npm package will end up in the npm tree. This is precisely why you sought assistance from require.resolve .

An alternative approach is to utilize the npm API (or CLI) and make a request using the command npm ls along with the —parseable option. This will result in:

Display output that can be parsed instead of presenting it in tree view.

… will output something like this:

/Users/me/my-project/node_modules/my-dep 

It’s important to note that when using this command, there may be irrelevant errors that are outputted to stderr, such as those related to extraneous installations. To address this issue, you can enable the flag labeled —silent (refer to loglevel in the documentation for more information).

By utilizing a child process, you can incorporate this instruction into your code. It is advisable to execute the instruction without the —silent flag to ensure that all errors are captured.

After detecting an error, you have the option to determine its severity. For example, the previously mentioned error regarding an unnecessary package can be disregarded.

Here’s an example of how the CLI can be utilized through a child process:

const exec = require('child_process').exec; const packageName = 'my-dep'; exec(`npm ls $ --parseable`, (err, stdout, stderr) => < if (!err) < console.log(stdout.trim()); // ->/Users/me/my-project/node_modules/my-dep > >); 

This can be utilized in an asynchronous flow by incorporating some closure magic.

const exec = require('child_process').exec; const async = require('async'); async.waterfall([ npmPackagePathResolver('my-dep'), (packagePath, callback) => < console.log(packagePath) // ->/Users/me/my-project/node_modules/my-dep callback(); > ], (err, results) => console.log('all done!')); function npmPackagePathResolver(packageName) < return (callback) => < exec(`npm ls $--parseable`, (err, stdout, stderr) => < callback(err, stdout.trim()); >); >; > 

How do I require something in root project directory from inside node, By making sure the current working directory is set to the project root so you can use process.cwd() to get access to the config file.

Читайте также:  Html select text length

Источник

Path

The node:path module provides utilities for working with file and directory paths. It can be accessed using:

The default operation of the node:path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the node:path module will assume that Windows-style paths are being used.

So using path.basename() might yield different results on POSIX and Windows:

To achieve consistent results when working with Windows file paths on any operating system, use path.win32 :

To achieve consistent results when working with POSIX file paths on any operating system, use path.posix :

On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, path.resolve(‘C:\\’) can potentially return a different result than path.resolve(‘C:’) . For more information, see this MSDN page.

M path.basename(path[, suffix])

The path.basename() method returns the last portion of a path , similar to the Unix basename command. Trailing directory separators are ignored.

Although Windows usually treats file names, including file extensions, in a case-insensitive manner, this function does not. For example, C:\\foo.html and C:\\foo.HTML refer to the same file, but basename treats the extension as a case-sensitive string:

A TypeError is thrown if path is not a string or if suffix is given and is not a string.

Provides the platform-specific path delimiter:

The path.dirname() method returns the directory name of a path , similar to the Unix dirname command. Trailing directory separators are ignored, see path.sep .

A TypeError is thrown if path is not a string.

The path.extname() method returns the extension of the path , from the last occurrence of the . (period) character to end of string in the last portion of the path . If there is no . in the last portion of the path , or if there are no . characters other than the first character of the basename of path (see path.basename() ) , an empty string is returned.

A TypeError is thrown if path is not a string.

  • pathObject Object Any JavaScript object having the following properties:
    • dir string
    • root string
    • base string
    • name string
    • ext string

    The path.format() method returns a path string from an object. This is the opposite of path.parse() .

    When providing properties to the pathObject remember that there are combinations where one property has priority over another:

    • pathObject.root is ignored if pathObject.dir is provided
    • pathObject.ext and pathObject.name are ignored if pathObject.base exists

    The path.isAbsolute() method determines if path is an absolute path.

    If the given path is a zero-length string, false will be returned.

    A TypeError is thrown if path is not a string.

    The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.

    Zero-length path segments are ignored. If the joined path string is a zero-length string then ‘.’ will be returned, representing the current working directory.

    A TypeError is thrown if any of the path segments is not a string.

    The path.normalize() method normalizes the given path , resolving ‘..’ and ‘.’ segments.

    When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator ( / on POSIX and \ on Windows). Trailing separators are preserved.

    If the path is a zero-length string, ‘.’ is returned, representing the current working directory.

    Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator ( \ ):

    A TypeError is thrown if path is not a string.

    The path.parse() method returns an object whose properties represent significant elements of the path . Trailing directory separators are ignored, see path.sep .

    The returned object will have the following properties:

    A TypeError is thrown if path is not a string.

    The path.posix property provides access to POSIX specific implementations of the path methods.

    The API is accessible via require(‘node:path’).posix or require(‘node:path/posix’) .

    The path.relative() method returns the relative path from from to to based on the current working directory. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.

    If a zero-length string is passed as from or to , the current working directory will be used instead of the zero-length strings.

    A TypeError is thrown if either from or to is not a string.

    The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

    The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo , /bar , baz , calling path.resolve(‘/foo’, ‘/bar’, ‘baz’) would return /bar/baz because ‘baz’ is not an absolute path but ‘/bar’ + ‘/’ + ‘baz’ is.

    If, after processing all given path segments, an absolute path has not yet been generated, the current working directory is used.

    The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

    Zero-length path segments are ignored.

    If no path segments are passed, path.resolve() will return the absolute path of the current working directory.

    A TypeError is thrown if any of the arguments is not a string.

    Provides the platform-specific path segment separator:

    On Windows, both the forward slash ( / ) and backward slash ( \ ) are accepted as path segment separators; however, the path methods only add backward slashes ( \ ).

    On Windows systems only, returns an equivalent namespace-prefixed path for the given path . If path is not a string, path will be returned without modifications.

    This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns path without modifications.

    The path.win32 property provides access to Windows-specific implementations of the path methods.

    The API is accessible via require(‘node:path’).win32 or require(‘node:path/win32’) .

    Источник

Оцените статью