Paths

Question Click to View Answer

What does the following code print to the console?

const path = require('path');
const r = path.normalize("/animals//lion.jpg");
console.log(r);

"/animals/lion.jpg" is printed.

The normalize() method removes extra slashes in a path.

What does the following code print to the console?

const path = require('path');
const r = path.normalize("/animals/cats/small/..");
console.log(r);

"/animals/cats" is printed.

The normalize() method follows Unix conventions so .. refers to the parent directory.

What does the following code print to the console?

const path = require('path');
const r = path.join("/users", "phil", "/funny//pics/");
console.log(r);

"/users/phil/funny/pics/" is printed.

The path() method concatenates directories into a well formatted path. The path() method also normalizes the path by eliminating duplicate forward slashes.

What does the following code print to the console?

const path = require('path');
const r = path.join("superheros", "x_men");
console.log(typeof(r));

"string" is printed.

The path method return strings. They don't return special objects like some other languages.

What does the following code print to the console?

const path = require('path');
const r = path.dirname("/cities/east_coast/new_york.txt");
console.log(r);

"/cities/east_coast" is printed.

The dirname() method returns the parent directory of a file. The new_york.txt file is stored in the /cities/east_coast directory, which is the dirname in this example.

What does the following code print to the console?

const path = require('path');
const r = path.basename("/cities/midwest/kansas_city.txt");
console.log(r);

kansas_city.txt is printed.

The basename() method returns the filename (aka basename).

What does the following code print to the console?

const path = require('path');
const r = path.extname("/cities/images/seattle.jpg");
console.log(r);

.jpg is printed.

The extname() method returns the extension of the file.

What does the following code print to the console?

const fs = require('fs');
fs.exists('/etc/passwd', function(exists) {
  if (exists) {
    console.log("File exists!");
  } else {
    console.log("File doesn't exist :(");
  }
});

"File exists!" is printed.

The exists() method takes a path as the first argument and a callback function as the second argument. The callback function can implement logic depending on if the file exists or not.

What does the following code print to the console?

const fs = require('fs');
fs.exists('/something_crazy', function(exists) {
  if (exists) {
    console.log("File exists!");
  } else {
    console.log("File doesn't exist :(");
  }
});

"File doesn't exist :(" is printed.