Replacing string contains forward slashes in __filename in NodeJs - node.js

I'm using __filename variable in NodeJS ES7 and would like to replace file path
from
c:/web/google-web/tests/selenium/tests/desktop/main/login.js
to
c:/web/google-web/Results/desktop/main/login.log
I tried this code:
console.log(__filename.replace("tests/selenium/tests", "Results").replace('.js','.log'));
console.log(__filename.replace("tests\/selenium\/tests", "Results").replace('.js','.log'));
console.log(__filename.replace(/\//g, "-").replace("tests-selenium-tests", "Results").replace('.js','.log'));
I tried How to globally replace a forward slash in a JavaScript string? too but no luck.

If what you've tried isn't working I can only assume that __filename isn't what you expect it to be.
Your first two examples work just fine (the third doesn't switch hyphons back to slashes), and you can verify this by running:
"c:/web/google-web/tests/selenium/tests/desktop/main/login.js".replace("tests/selenium/tests", "Results").replace('.js','.log') === "c:/web/google-web/Results/desktop/main/lfghogin.log"; // true
Since your path starts c:/ I'm guessing you're on Windows? If so, you've got the slashes the wrong way round in your replacement.
If you want something generic to handle that then use .replace(/tests[\\/]selenium[\\/]tests/,'Results')

Related

How to copy part of a URL to a redirect path

I am trying to redirect a path e.g. www.something.com/apple/pie to www.something.com/tickets/pie-details
This is what I have tried but doesn't work:
if (req.url ~ "^/apple/.*") {
set req.url = "^/tickets/.*-details";
error 701 req.url;
}
Am I missing something?
You either need to capture the matches from the regex, or if it is simple just replace using regsub()
However I have read that these are no longer bundled in core varnish so you might need a vmod. This one appears to be the one you need: https://gitlab.com/uplex/varnish/libvmod-re
Here are some docs on how this can be used: https://docs.fastly.com/en/guides/vcl-regular-expression-cheat-sheet#capturing-matches
Basically the re object lets you use the matched portion to then assemble the new url using string operations.
All of the above is speculative using my knowledge of vcl and regex, but I personally have not tried it.

Remove filename.extension in url using nodejs

I'm a beginner in nodejs, so please excuse if this question already answered. I tried multiple methods but didn't work for me.
I'm trying to remove the filename.extension in http url
For example:
http://somedomain.com/path1/path2/path3/myfile.txt
to
http://somedomain.com/path1/path2/path3/
The filename in the url is dynamic, so I cannot use "myfile.txt" explicitly in the code.
I'm not using any web frameworks, But I have http://stringjs.com library
Using a Regular Expression:
'http://somedomain.com/hello1/hello2/hello3/myfile.txt'.replace(/\/\w+\.\w+$/, '');
The regular expression matches two strings separated by a . and preceeded by a / (/myfile.txt in your case), which is then being replaced by an empty string. This method works in node as well as in pure javascript.
Using node.js' path module:
let path = require('path');
let parsed = path.parse('http://somedomain.com/hello1/hello2/hello3/myfile.txt');
console.log(parsed.dir) // => http://somedomain.com/hello1/hello2/hello3
node.js has a built-in module for parsing paths. It is however not made for parsing URIs, but should work just fine in your case.
Splitting, Slicing and Joining
let url = 'http://somedomain.com/hello1/hello2/hello3/myfile.txt';
url.split('/').slice(0, -1).join('/');
Split the url at every /, remove the last element from the resulting array (myfile.txt) and join them back together with / as the separator.
You can do it like this:
var path = 'http://somedomain.com/hello1/hello2/hello3/myfile.txt';
path = path.split('/');
path.splice(path.length-1,1);
path = path.join('/');

How to make a request in Node.js with backslashes in the path?

I'm using the request npm module to access a REST service, that needs at some point requires a backslash (\) in part of the path to escape a especial character (it implements a small query DSL).
To my surprise, request is converting those backslashes to forward slashes (/). I've drilled down the problem a little bit more and it seems that it is calling url.parse under the hood and that is the culprit. I can pass a url.parse result with the proper path, but I don't see any option to avoid the back to forward slash conversion.
The ugly option might be to hack the url.parse result myself...
You just need to encode the backslashes (%5C) so that node.js knows they're not part of the URL itself.

Node Path Normalise trailing periods .. and

Can anyone explain to me why this holds true:
Normalize a string path, taking care of '..' and '.' parts.
When multiple slashes are found, they're replaced by a single one;
when the path contains a trailing slash, it is preserved. On Windows
backslashes are used.
Example:
path.normalize('/foo/bar//baz/asdf/quux/..')
// returns '/foo/bar/baz/asdf'
When I would expect it to return
'/foo/bar/baz/asdf/quux'
This is from the Node Documentation
http://nodejs.org/api/path.html#path_path_normalize_p
Edit
After running some test I know "why" this is happening, but do not understand the logic behind it.
Below are three examples with their input and output.
/foo/bar//baz/asdf/quux/.. /foo/bar//baz/asdf
/foo/bar//baz/asdf/quux/. /foo/bar//baz/asdf/quux
/foo/bar//baz/asdf/quux/ /foo/bar//baz/asdf/quux/
So for the original I can see that the double period ".." removed the final folder and the single period "." removes the trailing slash. I understand that when including files in parental folders you would prefix a path with ../ I am assuming that you can actually place this anywhere within a path, although there seems little point to me currently to be able to place it say mid path.
A double colon (..) means the parent directory as is standard in Linux. So, /foo/bar//baz/asdf/quux/.. basically selects the parent directory of /foo/bar//baz/asdf/quux

how to deal with special characters in nodejs fs readdir function

I'm reading a directory in nodejs using the fs.readdir() function. You feed it a string containing a path and it returns an array containing all the files inside that directory path in string format. It does not work for me with special characters (like ï).
I came across this similar issue, however I am on OS X).
First I created a new dir called encoding and created a file called maïs.md (with my editor Sublime Text).
fs.readdir('encoding', function(err, files) {
console.log(files); // [ 'maïs.md' ]
console.log(files[0]); // maïs.md
console.log(files[0] === 'maïs.md'); // false
console.log(files[0] == 'maïs.md'); // false
console.log(files[0].toString('utf8') === 'maïs.md'); // false
});
The above test works correctly for files without special characters. How can I compare this correctly?
you character seems to be this one. You should try with
(1) console.log(files[0] == 'ma\u00EF;s.md');
(2) console.log(files[0] == 'mai\u0308;s.md');
If (1) works it could mean that the file containing your code is not saved in utf-8 format, so the node.js engine does not interpret correctly the ï character in your code.
If (2) works it could mean that the file system gives to the node engine the ï character in its decomposed unicode form (i followed by a diacritic ¨). cf #thejh answer
In this (2) case, use the unorm library available on npm to normalize the strings before comparing them (or the original UnicodeNormalizer)
https://apple.stackexchange.com/a/10484/23863 looks relevant – it's probably because there are different ways to express ï in utf8.

Resources