Alternative to path module that always uses forward-slashes? - node.js

I've been (mis)using the native path module for manipulating URL paths (e.g. using path.relative() to work out the shortest relative link from one URL path to another). But this breaks on Windows, because path uses backslashes on Windows.
Is there an alternative to path that always uses forward-slashes, regardless of OS?
(There is a url module but it doesn't have equivalents for path.relative, path.dirname, etc.)

Answering my own question...
It looks like Browserify's shim for path works well for this.
var path = require('path-browserify');
Works exactly like the native path module running on Unix, regardless of your OS.

You could use the slash module for this:
var path = require('path');
var slash = require('slash');
var yourPath = slash(path.join('foo', 'bar'));
// foo/bar

Related

rootDirName returning wrong part of the path

I have a Gulpfile which runs in the 'theme' folder of my project.
C:\wamp\www\mywebsitename\wp-content\themes\mythemename\gulpfile.js
In the gulpfiule, need to get the local website URL, which is basically just the 'mywebsitename' part of this path.
I have historically used this code to get it successfully:
"var rootDirName = path.basename(__dirname, '../../../');"
However I recently re-installed Windows, Node and Gulp, and now that line of code returns 'mythemename' instead of 'mywebsitename', ignoring the '../../../' argument.
If I remove that argument, it stil returns 'mythemename'.
I'm guessing some newer version of Gulp, Node or something in Windows has changed how this method works. Please can anyone suggest why this no longer works, or if there is a better way to always go 3 levels up the file tree from the gulpfile.js directory?
Worked it out myself.
const path = require('path');
var rootDirPath = path.join(__dirname, '../../../');
var rootDirName = path.basename(rootDirPath);
var url = 'http://localhost/' + rootDirName;
This will allow you to get the website's URL on localhost in Gulp and do what you need to with it (in my case, using the Critical CSS tool to scan the website and inline all the header CSS).

Is it possible to use computer path in Node?

Normally in node one would use a path similar to this:
../js/hereIsMyJs.js
However in mac for example (pc is different)
the path can be ~/Desktop/Ohms/js/hereIsMyJs.js
Is there any module or way to use the computer path I just presented in node?
I'm using a module that requires the path to where the file should be placed.
It has to work dynamic so the optimal solution would be for me just to feed it the "computer" path.
const fileName = '~/Desktop/Ohms/somewhere/here.jpg'
QRCode.toFile(fileName, 'https://example.com')
To achieve what you want, it's normal to use node's native path.resolve https://nodejs.org/api/path.html#path_path_resolve_paths
// Start from current directory, and gives absolute path valid to the current OS.
console.log( path.resolve("../js/hereIsMyJs.js") ); // ie: C:\\projects\\js\\hereIsMyJs.js
// It also accepts multiple arguments, so you can feed it partial paths
path.resolve( "..", "js" ,"hereIsMyJs.js" ); // same result as above.
Other things worth to mention:
The tilde character ~ is short for the home directory in the *nix world. And works most places not windows.
In node you can use require('os').homedir() to get the home directory
There is also __dirname (gives absolute path of the directory containing the currently executing file) and process.cwd() which gives the directory from where you executed your file
And finally there is path.join() which is similar to resolve, but works for joining relative paths, and doesn't care about the current directory.

Write file relative to server's absolute path in node.js

Does anyone know how I can write a file relative to my server's absolute path: /var/logs/.../? Right now I am building my path like: ../../../../var/logs. I am looking for something like:
server_root/var/logs
Thanks in advance!
You can use absolute paths (/var/...), just like any other system that uses paths.
You can get the current execution path of server using rootpath variable
var path = require('path'),
var rootPath = path.normalize(__dirname + '/..'); //_dirname is from nodejs
Now you can use this to get exact path of all the directories

Require for a relative path across modules

I have project A that has a config.json file in its root. The project has a dependency on external module B, calling B.setConfig('./config.json').
While inside B.setConfig(path), if I call fs.existsSync(path), it says Ok, file exists, but calling require(path) fails with Cannot find module "./config.json".
Is it possible to adjust the relative path while inside module B to make require work?
I would prefer not to call setConfig with the full path, as it makes things awkward.
I found it, eventually, that if we want to take a relative path from module A (call it remotePath), and use it within require in module B, then to get the full path inside module B we can use the following:
var path = require('path');
var fullPath = path.join(path.dirname(process.argv[1]), remotePath);
var moduleInsideA = require(localPath); // this now works
process.argv[1] gives us the module A start-up file, from which we take the directory path, and then join it with the remote relative path, which then gives us the full path.

How to resolve a relative path in node?

Came across this situation recently - I have an environment variable for a directory path like so:
var fooDir = process.env.FOO_DIR;
and I want to make sure this directory exists with a synchronous mkdir (at some point later):
fs.mkdirSync(fooDir, mode);
however if the user has supplied the environment variable via a realtive ~/ path node cannot resolve it
export FOO_DIR='~/foodir'
is there a way in node to resolve this without invoking a child process exec call to the actual shell? currently my solution is to do a replace myself like so:
fooDir = fooDir.replace(/^~\//, process.env.HOME + '/');
just curious if someone has a better solution.
You have it right: ~ is expanded by the shell, not the OS, just like *. None of the C file functions that node.js wraps handle ~ either, and if you want this you have to do the replacement yourself, just as you've shown. I've done this myself in C when supporting config files that allow relative file paths.
However, you should probably handle the case where HOME isn't defined; I believe this happens with non-interaction logins with bash, for example, and the user could always choose to unset it.
You can convert it to absolute path with path.join:
const path = require('path')
const absolutePath = path.join(process.cwd(), relativePath)
Check out Rekuire, it is a node module that solves the relative paths problem in NodeJs.

Resources