I want to read from a path and I wrote two different codes.The first code does not work but the second code works perfectly. I do not understand the differences. can someone explain to me what is going on? thanks.
the file is stored in /modules/config/
First Code:
var tmpModulePath = path.join('./modules/',"config/");
var moduleConfigInfo = require(tmpModulePath + "_test.js");
Second code:
var tmpModulePath = path.join('./modules/',"config/");
var moduleConfigInfo = require("./" + tmpModulePath + "_test.js");
from the first code, I do get this error: Can not find module ..._tset.csv
If you console.log the generated path you get this results:
First code block:
"modules/config/_test.js"
Second code block:
"./modules/config/_test.js"
In the second case, you have a relative path starting from your current directory (./). require will look for a modules folder starting from your current directory.
In the first case, the path is absolute, meaning that require will look for a modules folder starting from the root path of your filesystem.
I hope you understand the difference now.
What you really want to use in this case is path.resolve:
var tmpModulePath1 = path.resolve('./', 'modules/',"config/", 'test.js');
Check the answer to this question to understand the difference between .join and .resolve.
Related
I am quite new with Node.js.
There is a folder on my computer where I have several textfiles (.fw4 format). I could find all the text files with the node-dir module.
Furthermore I need to get some content of each file from specified columns. Actually this algorithm works fine, using the readline module.
I keep my files name in an array.
Something like this: [ '000037592.fw4', '000037593.fw4', '000037594.fw4' ]
What do I need actually? I would like that this whole system would work synchronously and when I get the first file content (000037592.fw4) it would log something like end of file. And it continues reading the other files from the array.
So far, it has not worked how I wanted.
Thank you so much in advance. I would appreciate any suggestion on how to get a solution for my problem.
Do something like:
var fileArray = [ '000037592.fw4', '000037593.fw4', '000037594.fw4' ];
var i = 0;
readNextFile();
function readNextFile(){
fs.readFile(fileArray[i++], function(result){
handleResult(result);
if(i < fileArray.length){
readNextFile();
}
});
}
Using Node.js, I am looking for a neat way of finding the most recent subdirectory in a directory where the subdirectory happens to be the last one if they are sorted alphabetically/numerically.
All the subdirectories are named by timestamp, like so:
- parent dir
--- 494985839399
--- 232111234483
--- 334433885832
--- 112221994948
... etc
Now I assume when you read a directory and iterate over its contents it's not guaranteed to be sorted by recency or alphabetically?
So, I am looking for a good way to find that subdir besides brute force O(n) search. Unfortunately I will obviously not know the name of the dir, thus making a search or sort necessary.
What's the best way to do this with Node? It can be synchronous or async because this is not for a server.
You can use readdir to get the directories in an array and then sort the array. Like this:
var fs = require('fs');
var result = fs.readdirSync('parentDir').sort().reverse();
var subdir = result[0];
This is not optimised at all (for example, you can make readdir async and make a custom sort function that sorts descending).
In one line:
var result = require('fs').readdirSync('parentDir').sort().reverse()[0];
(I did not test the code)
I'm trying to access a page from another domain, I can get all other html from php, but the files like images and audio files have relatives paths making them to be looked inside the local server whereas they're on the other server.
I've allowed cross-domain access though PHP from the other page.
header('Access-Control-Allow-Origin: *');
Then I use AJAX load to load that pages' content.
$('#local_div').load('page_to_load_on_side_B #div_on_that_page');
Now, the path looks like this:
../../user/6/535e55ed00978.jpg
But I want it to be full like.
http//:www.siteB.com/user/6/535e55ed00978.jpg
Correction: I have full access to both sites so I need to get the absolute paths from the site where these files are originating.
For this problem would use one of the following:
Server Side Approach
I would create a parameter in server B named for example abspath. When this param is set to 1 the script would start an output buffer ob_start() then before submiting would get ob contents with ob_get_clean() and finally using regular expressions make a replace of all urls for http//:www.siteB.com/. So, the script on server A would look like follows:
<?php
$abspath=(isset($_REQUEST["abspath"])?$_REQUEST["abspath"]:0);
if($abspath==1) ob_start();
// Do page processing (your actual code here)
if($abspath==1)
{
$html=ob_get_clean();
$html=preg_replace("\.\.\/\.\.\/", "http://siteb.com/");
echo $html;
}
?>
So in client side (site A) your ajax call would be:
$('#local_div').load('page_to_load_on_side_B?abspath=1#div_on_that_page');
So when abspath param is set to 1 site B script would replace relative path (note I guessed all paths as ../..) to absolute path. This approach can be improved a lot.
Client Side Approach
This replace would be done in JavaScript locally avoiding changing Server B scripts, . The replacements in Javascript would be the same. If all relative paths starts with ../.. the regex is very simple, so in site A replace $('#local_div').load('page_to_load_on_side_B #div_on_that_page'); for the following (note that I asume all relatives urls starts with ../..):
$.get('page_to_load_on_side_B #div_on_that_page', function(data) {
data=data.replace(/\.\.\/\.\.\//, 'http://siteb.com/');
$('#local_div').html(data);
});
That will do the replacement before setting html to DIV so images will be loaded from absolute URL.
Ensure full CORS access to site B.
The second approach is clean than the first so I guess would use Javascript to do the replacements, both are the same only changes where the replace is done.
There is a PHP function that can make absolute path from relative one.
realpath()
If you mean URL path, simply replace all occurences of "../" and add domain in front.
Try this one:
function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
Also you can find below solution:
In general, there are 2 solutions to this problem:
1) Use $_SERVER["DOCUMENT_ROOT"] – We can use this variable to make all our includes relative to the server root directory, instead of the current working directory(script’s directory). Then we would use something like this for all our includes:
include($_SERVER["DOCUMENT_ROOT"] . "/dir/script_name.php");
2) Use dirname(FILE) – The FILE constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:
include(dirname(__FILE__) . "/dir/script_name.php");
You may also use basename() together with dirname() to find the included scripts name and not just the name of the currently executing script, like this:
script_name = basename(__FILE__);
I personally prefer the second method over the first one, as it gives me more freedom and a better way to create a modular web application.
Note: Remember that there is a difference between using a backslash “\” and a forward (normal) slash “/” under Unix based systems. If you are testing your application on a windows machine and you use these interchangeably, it will work fine. But once you try to move your script to a Unix server it will cause some problems. Backslashes (“\”) are also used in PHP as in Unix, to indicate that the character that follows is a special character. Therefore, be careful not to use these in your path names.
I'm stuck on a roadblock with the simplest of things. In Drupal 6, I'm trying to take a user-entered path to an image and output that image to the page. Here's a bit of code:
$slogan_image = theme('image', $slogan_image_path);
dpm("\$slogan_image_path = '$slogan_image_path'");
dpm("\$slogan_image = '$slogan_image'");
The devel output reads:
$slogan_image_path = '/sites/default/files/images/Family.jpg'
$slogan_image = ''
There is an image at '/sites/default/files/images/Family.jpg'; if I browse to www.mysite.com/sites/default/files/images/Family.jpg, the image will be displayed.
What am I doing wrong? Thanks.
The problem was that my path began with a slash. Drupal paths don't have that initial slash. Drupal being open source, I could look refer to the Drupal 6 api docs and see the code for theme_image included this line:
$url = (url($path) == $path) ? $path : (base_path() . $path);
showed me that Drupal would prepend my path with the base_path(). Executing that code myself, in an Execute PHP page, allowed me to see that theme_image would wind up using //sites/default/files/images/Family.jpg as the $url, clearly an illegal value.
I thought I'd append this short explanation to my trivial problem to help rank beginners see how I debugged it.
<rant>
firstly, I've searched a lot and every single question / blog asks/tells about how to convert physical path to relative, never the other way around. If I've missed that question here, I am sorry.
<rant />
So, I have a directory structure very similar to this:
Root
|....Components
|....Classes
|....Utils
|....FileUtils
|....Assets //this is a folder
|....FileAccess.cs
So, in my FileAccess.cs I just want to read the content of a text file and display it on a page.
in my webpage.aspx.cs I am calling the getFileContent() which is in utils.
so the relative path from FileAccess.cs is Assets\spec.txt
So, how on earth can I access that with code?
this is what I am trying / tried:
//function getFileContent() content..
private const string QuestionnairePath = #"Assets\";
return Server.MapPath(QuestionnairePath + "spec.html");
it ALWAYS throws file not found exception and upon debugging it's not selecting the right folder.
I have even tried this:
private const string QuestionnairePath = #"~Utils\FileUtils\Assets\";
that doesn't work either.
This must be very easy. Just can't figure it out, for the life of me. I hate being a newbie sometimes.
Help please,
Thanks.
ps: Ideally, I would just want to use relative path: Assets\ - wonder if that is possible.