I want to read a file with commander:
#!/usr/bin/env node
var fs = require('fs')
var program = require('commander')
program
.version('0.0.1')
.usage('<keywords>')
.parse(process.argv)
if(!program.args.length) {
program.help()
} else {
var filename = program.args
console.log('keys: ' + filename)
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err
console.log(data)
})
}
$ ./m2k.js test.txt
However, I get the this error:
fs.js:430
binding.open(pathModule._makeLong(path),
^
TypeError: path must be a string
What am I doing wrong?
(I have a file called test.txt in the same folder as m2k.js.)
If you print the type of program.args or the program.args itself, you will know that its an Array.
console.log(Object.prototype.toString.call(program.args), program.args);
// [object Array] [ 'test.txt' ]
So, you need to use the correct index to be used like this
var filename = program.args[0];
I think the result of console.log('keys: ' + filename) is not helping you much. It is because when you use + operator, it will try to convert the filename object to a string and the String array converted to a string normally just has comma separated strings. You can check that like this
console.log(['a'].toString(), ['a', 'b'].toString());
// a a,b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With