Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing a file path in node.js

Tags:

node.js

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!

like image 262
antun Avatar asked Dec 15 '22 09:12

antun


1 Answers

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);
});
like image 98
Jonathan Lonowski Avatar answered Jan 08 '23 04:01

Jonathan Lonowski