最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: path must be a string with commander - Stack Overflow

programmeradmin1浏览0评论

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.)

Share Improve this question asked Feb 25, 2015 at 14:28 wycwyc 55.3k82 gold badges256 silver badges439 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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 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
发布评论

评论列表(0)

  1. 暂无评论