ES6 and Node static variables

I have searched all over for a way to make variables static and can’t find one that works. For example, I have a class with a static method that requires the use of fs from node:

export class Global {

   static read(file) {
      this.fs.//etc
   }

}

But obviously, there is no this.fs, because the method is static. How can I work around this?

1 Like

Sadly ES6 class definitions can only contain methods, not data properties. I think that will change in the future, but for now we’ll have to work around it.

You could work around it with a module-global variable.

let fs = require('fs');

export class Global {

   static read(file) {
      fs.//etc
   }

}

Or you could attach data to the class after its definition.

export class Global {

   static read(file) {
      Global.fs.//etc
   }

}

Global.fs = require('fs');

Or you could set it in the constructor, with an “if” test to set it just once.

export class Global {

    constructor() {
        if (!Global.fs) {
            Global.fs = require('fs');
        }
    }

   static read(file) {
      Global.fs.//etc
   }

}
2 Likes

Much easier than I thought! Thank you!

I found another way to do it, for anyone curios:

export var fs = require('fs');

export class Global {
   static read(file) {
      fs.readFile();
   }
}

Then you can use it in another class:

import {Global} from ""

Global.fs.readFile();

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.