I want to read a file with mander:
#!/usr/bin/env node
var fs = require('fs')
var program = require('mander')
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
.)
I want to read a file with mander:
#!/usr/bin/env node
var fs = require('fs')
var program = require('mander')
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
.)
3 Answers
Reset to default 6If 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 ma separated strings. You can check that like this
console.log(['a'].toString(), ['a', 'b'].toString());
// a a,b
Your filename
is actually an array of all arguments passed to your application.
add a console.log(program.args)
to your code to see its contents.
var filename = program.args;
The type of filename is a string object and not a string literal, because
typeof filename === 'object' // true
typeod filename === 'string' // false
simply do this to resolve that problem:
var filename = String(program.args);
because
new String(arg); //creates a new instance of the String object
and
process.argv // is an array of String objects not literals
while
String(arg); // tries to turn all objects into a string literal