Trying to spread an array as arguments into the join
method on path
in node, but no luck:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput);
var target = path.join.apply(null, paths);
I get:
TypeError: Arguments to path.join must be strings
One possible solution is just give the method a string of arguments. I don't even know if that's possible. But just curious if there is a trick in JavaScript in situations like this. Or am I approaching it totally wrong ?
Trying to spread an array as arguments into the join
method on path
in node, but no luck:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput);
var target = path.join.apply(null, paths);
I get:
TypeError: Arguments to path.join must be strings
One possible solution is just give the method a string of arguments. I don't even know if that's possible. But just curious if there is a trick in JavaScript in situations like this. Or am I approaching it totally wrong ?
Share Improve this question edited May 6, 2015 at 14:29 AJ Meyghani asked May 6, 2015 at 3:34 AJ MeyghaniAJ Meyghani 4,5991 gold badge32 silver badges36 bronze badges 10 | Show 5 more comments2 Answers
Reset to default 17You are pushing an array onto an array, resulting in
[ __dirname, [ 'app', 'js' ] ]
path.join
has no idea what to do with these nested arrays. apply
does not somehow magically flatten its input. The error message from path.join
could not be clearer: it wants its arguments to be strings, not arrays. So instead use concat
to combine the arrays:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
// Use concat here
paths = paths.concat(userInput);
var target = path.join.apply(null, paths);
An alternative would be
paths.push.apply(paths, userInput);
which would push the elements of userInput
onto paths
one by one.
If you are using ES6, then you could use the spread operator and write this as:
paths.push(...userInput)
or
paths = [...paths, ...userInput]
or just directly
var target = path.join(...paths, ...userInput)
Actually the issue was that I was overthinking the problem. Instead of concatenating the paths array with the other array, I was pushing an array into the paths array:
var path = require("path");
var paths = [__dirname];
var userInput = ["app", "js"];
paths.push(userInput); // x
The problem can be avoided by just paths.concat(userInput)
. Then you can spread the arguments:
path.join.apply(null, paths.concat(userInput));
Thanks to @torazaburo for pointing it out.
inquirer
. Maybe I should rethink what I get from the user. I get path values like "app/js" and then split it into an array. And then I pass it topath.join
to construct the path if that makes sense. – AJ Meyghani Commented May 6, 2015 at 3:42