I have a node.js script that takes a filename argument, which it then consumes using require():
json2csv.js
var filename = process.argv[2];
var parsedJSON = require(filename);
I run this as follows:
$ node json2csv.js ./inputFile.json
This works so long as I either explicitly prefix the file (if local) with "./" or I use an absolute file path. However, if I omit the "./", e.g.:
$ node json2csv.js inputFile.json
I get a "Cannot find module" error, because node is interpreting the filename as a module name. Is there a standard way to munge file paths in node so that they are output either as an explicit local path or an absolute one?
I know it's not difficult to write for my scenario; I'm just looking for a standard way that would work across platforms. I found Path.normalize(), but that actually strips any leading "./".
Thanks!
You can use path.resolve()
, optionally passing process.cwd()
for from
:
var path = require('path');
var filepath = path.resolve(process.cwd(), process.argv[2]);
Examples:
console.log(path.resolve('/foo/bar', 'baz')); // "/foo/bar/baz"
console.log(path.resolve('/foo/bar', './baz')); // "/foo/bar/baz"
console.log(path.resolve('/foo/bar', '/baz')); // "/baz"
Though, to avoid caching with require()
, you should read the file directly:
fs.readFile(filepath, function (err, jsonData) {
var result = JSON.parse(jsonData);
});
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