How can I check whether a variable is defined in Node.js?

前端 未结 6 454
不知归路
不知归路 2021-01-31 01:18

I am working on a program in node.js which is actually js.

I have a variable :

var query = azure.TableQuery...

looks this line of the

6条回答
  •  余生分开走
    2021-01-31 01:50

    For me, an expression like

    if (typeof query !== 'undefined' && query !== null){
       // do stuff
    }
    

    is more complicated than I want for how often I want to use it. That is, testing if a variable is defined/null is something I do frequently. I want such a test to be simple. To resolve this, I first tried to define the above code as a function, but node just gives me a syntax error, telling me the parameter to the function call is undefined. Not useful! So, searching about and working on this bit, I found a solution. Not for everyone perhaps. My solution involves using Sweet.js to define a macro. Here's how I did it:

    Here's the macro (filename: macro.sjs):

    // I had to install sweet using:
    // npm install --save-dev
    // See: https://www.npmjs.com/package/sweetbuild
    // Followed instructions from https://github.com/mozilla/sweet.js/wiki/node-loader
    
    // Initially I just had "($x)" in the macro below. But this failed to match with 
    // expressions such as "self.x. Adding the :expr qualifier cures things. See
    // http://jlongster.com/Writing-Your-First-Sweet.js-Macro
    
    macro isDefined {
      rule {
        ($x:expr)
      } => {
        (( typeof ($x) === 'undefined' || ($x) === null) ? false : true)
      }
    }
    
    
    // Seems the macros have to be exported
    // https://github.com/mozilla/sweet.js/wiki/modules
    
    export isDefined;
    

    Here's an example of usage of the macro (in example.sjs):

    function Foobar() {
        var self = this;
    
        self.x = 10;
    
        console.log(isDefined(y)); // false
        console.log(isDefined(self.x)); // true
    }
    
    module.exports = Foobar;
    

    And here's the main node file:

    var sweet = require('sweet.js');
    
    // load all exported macros in `macros.sjs`
    sweet.loadMacro('./macro.sjs');
    
    // example.sjs uses macros that have been defined and exported in `macros.sjs`
    var Foobar = require('./example.sjs');
    
    var x = new Foobar();
    

    A downside of this, aside from having to install Sweet, setup the macro, and load Sweet in your code, is that it can complicate error reporting in Node. It adds a second layer of parsing. Haven't worked with this much yet, so shall see how it goes first hand. I like Sweet though and I miss macros so will try to stick with it!

提交回复
热议问题