Raja Raja - 3 months ago 11
Node.js Question

Node Js : Unable to find error in below file filter code

I have written small code to get files filtered by extension. And my point of view logic is fine but I am unable to point out why I am not getting expected output.

Please have a look.

CODE

var fs = require('fs')
var path = require('path')

path_name = process.argv[2]
ext_name = "."+process.argv[3]

var filter_function = function ( path_name,exthide_name,callback) {
fs.readdir(dirpath,function(err,list) {
if(err) return console.error(err)

for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}
})
}

module.exports=filter_function


Output :

linuxmen@linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
linuxmen@linuxmen-fresh:~/test/test1$


But I have so many files with
js
extension in that directory.

Proof:

linuxmen@linuxmen-fresh:~/test/test1$ ls *js
check_mod1.js ex1.js ex2.js ex3.js ex4.js ex5.js ex6.js ex7.js ex8.js filter.js filter_use.js modse.js ownModuleNode.js se.js use_mod1.js using_module.js


Could please help , what I am missing.

Update - 1 : I am using above code a module file and calling it here.

File using above code

var mymodule = require('./ownModuleNode')
mymodule.filter_function(process.argv[2],process.argv[3])


Update 2 :

var fs = require('fs')
var path = require('path')


path_name = process.argv[2]
ext_name = "."+process.argv[3]

console.log("path_name :",path_name,"extname:",ext_name)
var filter_function = function ( path_name,ext_name,callback) {
fs.readdir(path_name,function(err,list) {
if (err) console.error(err)
console.log(list)
for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}

})
}

module.exports=filter_function


Output:

linuxmen@linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
pathanme : /home/linuxmen/test/test1/ extname: .js


Thank you.

Answer

It looks like you are exporting the function directly. When you require() it, you just getting the function. You'll need to use your module in your application. Put this in 'app.js' in the same dir as ownModuleNode.js:

var filterFunction = require('./ownModuleNode');
filterFunction(process.argv[2], process.argv[3]);

Then call it with:

node app ~/Documents/dev/project .js

Outputs:

app.js
ownModuleNode.js

Note that when you pass the extension, you need the preceding dot because path.extname() returns the dot.