George Guo
George Guo

Reputation: 111

Case sensitive issue in node.js

I have 2 files, extendableError.js

class ExtendableError extends Error {
  constructor(message) {
    super(message)
    this.name = this.constructor.name
    this.message = message
    if (typeof Error.captureStackTrace === 'function') {
      Error.captureStackTrace(this, this.constructor)
    } else {
      this.stack = new Error(message).stack
    }
  }
}

module.exports = ExtendableError

duplicatedError.js

const ExtendableError = require('./ExtendableError')

class DuplicatedError extends ExtendableError {
  constructor(message) {
    super(message)
  }
}

module.exports = DuplicatedError

Below is my testing code,

const DuplicatedError = require('./duplicatedError');
const ExtendableError = require('./ExtendableError');
const ExtendableError1 = require('./extendableError');


try{
    throw new DuplicatedError('hahah');
}catch(err){
    console.log(err instanceof ExtendableError); // true
    console.log(err instanceof ExtendableError1); // false
}

The test is on my mac book, why is that happen? Only the 1st charater was uppercase has different results. i don't understand.

Upvotes: 1

Views: 1996

Answers (2)

Howard
Howard

Reputation: 4604

Firstly, for compatibility reason, macOS chose a case-insensitive file system. But it doesn't mean you have to bear it, Disk Utility can be used to reformat the partition to case-sensitive mode. If You do that, node.js will report error to you because of the wrong module name you are trying to require.

Then, let's talk about your test result. The key issue is which one you require in duplicatedError.js, if you change it a little bit:

//change the required name to lowercase extendableError
const ExtendableError = require('./extendableError')

class DuplicatedError extends ExtendableError {
  constructor(message) {
    super(message)
  }
}

module.exports = DuplicatedError

The test result will be:

false
true

You can even try to modify duplicatedError.js like below:

//change the required name to extENDableError
const ExtendableError = require('./extENDableError')

class DuplicatedError extends ExtendableError {
  constructor(message) {
    super(message)
  }
}

module.exports = DuplicatedError

The result shall be

false
false

So i think it's not about module caching, you have two things to be clear here:

  1. macOX is case-insensitive file system by default
  2. even you have only one file extendableError.js, but you require twice with different names, like: require(./extendableError), require(./ExtendableError), require(./extENDableError), trey will be treated as three modules.

Upvotes: 1

Paul
Paul

Reputation: 36339

Macs are based on BSD UNIX, so the file system is case sensitive.

As a side note, it’s common to not use camecase for file names, eg:

  var extendableError = require(‘./extendable-error’)

Upvotes: 2

Related Questions