Retrieving files from Directory Node Js - node.js

I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.
var fs = require('fs');
var files = fs.readdirSync('./application/models/');
for(var i in files) {
var definition = require('../application/models/'+files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}
I am getting error for line number 2 .
ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)
I have application/models on the same dir. I already checked for '/application/models/' and
'application/models/' but failed. I can see the same thing running on server.
Please help
Thanks

If you are using relative path when calling readdirSync, make sure it is relative to process.cwd().
However, "require" should be relative to the current script.
For example, given the following structure
server.js (node process)
/lib/importer.js (the current script)
/lib/application/models/
you may need to write importer.js as:
var fs = require('fs');
var files = fs.readdirSync('./lib/application/models/');
for (var i in files) {
var definition = require('./application/models/' + files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}

Have you tried the following?
var files = fs.readdirSync(__dirname+'/application/models/');

Related

Absolute path to file throws error?

Recently I started with NodeJS and I found the require() function.
I have two JS files:
main.js in C:/Users/Admin folder and,
test.js in F: drive
Here is my test.js file:
function log(name) {
console.log(name);
}
module.exports.log = log;
and here is my main.js file:
var myModule = require("/F:/test");
myModule.log("Anonymous");
But when I type...
C:\Users\Admin>node main.js
in Node.js CMD, I get the following error statement:
Error: Cannot find module '/F:/test'
Help me to figure out the error!
You are giving the path of the file wrong.
It should be F:/test instead of /F:/test.
You can use path module to resolve the path by path.resolve and check what it resolves to. In your case it is resolving to C:\F:\test.
Update
You can check to what your provided path resolves to like below
const path = require('path');
let p = path.resolve('/F:/test');
console.log(p);// C:\F:\test
Use path module instead of specifying explicit path separators.
var path = require('path');
modulepath = path.join('F:','test');
var myModule = require(modulepath);

node_modules path programmatically

I am using protractor and I want to get programmatically the npm node_modules path from the global system.
For example my selenium jar is installed here:
C:/Users/myuser/AppData/Roaming/npm/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.7.1.jar
and I wanted to get
C:/Users/myuser/AppData/Roaming/npm/node_modules/
or
C:/Users/myuser/AppData/Roaming/npm/node_modules/protractor/node_modules/
I wrote this small script, which will look for my jar in the paths
var path = require('path');
var fs = require('fs');
var paths = path.getModulePaths()
for (i=0;i<paths.length;i++) {
file = path.join(paths[i],'webdriver-manager','selenium','selenium-server-standalone-3.7.1.jar')
if (fs.existsSync(file)) {
var seleniumServerJar = file
continue
}
}
here I supposed that this function is available
var paths = path.getModulePaths()
but it's not. I used to write an equivalent in Python, which is:
import sys
print sys.path
I guess you are expecting to start a webdriver manager programatically. Try below code:
var pkgPath = require.resolve('protractor');
var protractorDir = path.resolve(path.join(path.dirname(pkgPath), '..', 'bin'));
var webdriverManagerPath = path.join(protractorDir, '/' + 'webdriver-manager'));

How to read from a specified file which is in a folder below without knowing the absolute path

So I have my project directory:
Here I read ArticleFile:
function _getDataFromFile() {
var jsonArray = csvjson.toObject(fs.readFileSync('ArticleFile.csv', { encoding: 'utf8' }));
var result = [];
for (var idx = 0; idx < jsonArray.length; idx++) {
var currArt = jsonArray[idx];
// if (!checkIfElementIsArticle(currArt)) throw "loaded object IS NOT an article!";
result.push(new Article(currArt.imageLocation, currArt.title, currArt.description, parseInt(currArt.quantity),parseInt(currArt.price)));
}
return result;
}
The problem is if "ArticleFile.csv" is in lets say contentsKopie I have to know the absolute path such as : C:\Users\noone_000\Desktop\BSD\Hausübungen\WebServer\WebServer\contentsKopie\ArticleFile.csv . How can I set the path like: fs.readFileSync('/ContentsCopie/ArticleFile.csv', { encoding: 'utf8' })
PS: csvjson is a module (require("csvjson"))
When you start the path with / it is interpreted as an absolute path. If you want to open a file in sub directory, you can use ./ContentsCopie/ArticleFile.csv
The . in front of the slash means that the path is relative to the current directory.
Conversely, if you needed to go up a level you can prefix your path with ..
Isn't ./contentsKopie/ArticleFile.csv enough?
When using /contentsKopie/ArticleFile.csv it's actually looking in C:/contentsKopie/ArticleFile.csv. So you have to prepend your path with a . to tell it to start at the working directory (WebServer here).
Otherwise, you can have the absolute path of the current file with __dirname then you could compose your path using the path module from node.
var path = require('path');
var article = path.join(__dirname, './contentsKopie/ArticleFile.csv');
This way, you'll get the absolute path of your file.

Get filepath/name of a File Descriptor in node.js

How do you get fullpath from a file descriptor in node?
var fs = require('fs')
var fd = fs.openSync('package.json', 'r')
console.log(fd) // 10
console.log(get_file_path_from_fd(fd)) // HELP
Edit: I have found this
> fs.openSync('.', 'r')
10
> fs.readlinkSync('/proc/self/fd/10')
'/home/alfred/repos/test
but i didn't find proc folder in Mac
Considering that you're loading a file that is in the same directory as the script, you could just use the __dirname global to find the current directory.
https://nodejs.org/docs/latest/api/globals.html#globals_dirname
In fact, I prefer to load files using __dirname as part of the path for the fs module as a good practice. For example, this is from a Discord bot I have...
var tokenJSON = require( __dirname + '/json/discord_token.json');
Edit: So to put this into the answer itself; your fd variable contains the data that was loaded from the file, but it is completely disconnected from the file it came from originally. If you are being given an arbitrary file to load and you would like to have the path, we need to know more about how that file is being provided to you. When the file is given to you there should be a path included (so the script can locate the data!) and that is what you want. If there is no path like in your example, then that means the relative paths are the same and it's the current directory.
const {execSync} = require('child_process')
const fs = require('fs')
var fd = fs.openSync('package.json', 'r')
var fullpath = execSync(`lsof -a -p ${process.pid} -d ${fd}`).toString().split('\n')[1].split(/\s+/).pop()
console.log(fullpath) // result: /fullpath/package.json

how to use gulp-filter with main-bower-files to filter on directory in the middle

I want to filter just the files which include the directory ui-router somewhere in the middle of the path.
I have the following code:
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
var debug = require('gulp-debug');
var gulpFilter = require('gulp-filter');
gulp.task('default',function() {
var bower_files = mainBowerFiles();
var js_filter = gulpFilter(['**/*.js']);
gulp.src(bower_files)
.pipe(js_filter)
.pipe(debug({title: 'unicorn:'}))
var js_filter = gulpFilter(['**/ui-router/**']);
gulp.src(bower_files)
.pipe(js_filter)
.pipe(debug({title: 'unicorn1:'}))
});
The output is:
[12:10:53] unicorn: bower_components\ngstorage\ngStorage.js
[12:10:53] unicorn: bower_components\ui-router\release\angular-ui-router.js
[12:10:53] unicorn: bower_components\x2js\xml2json.min.js [12:10:53]
unicorn1: 0 items
Meaning that ['**/*.js'] works to filter out all js files.
But ['**/ui-router/**'] does not work. What is problematic with this pattern?
I read the following doc https://github.com/isaacs/node-glob and i don't see why it should not work.
You can filter the result of main-bower-files:
var files = mainBowerFiles(/\/ui\-router\//);
After hacking with this a long time i found the issue.
In gulp-filter the vinyl file.relative property is sent.Comment from Sindre Sorhus
In our case the files are without globs(What i understand) and therefore we get just the name of the file without the directory.
The solution is to write instead of gulp.src(bower_files) gulp.src(bower_files,{base:__dirname})
Here we say gulp from where to start the relative file.

Resources