Tag: javascript

  • JavaScript ISO date with local timezone

    It seems JS has until today no native (!) solution to get an ISO 8601 date & time string in the local time zone (it’s always in UTC). (Super weird, but okay).

    I updated the solution on Stackoverflow a bit using “new” ES2017 functionality like this:

    function getISOLocalString() {
      let date = new Date();
      let tzo = -date.getTimezoneOffset();
    
      if (tzo === 0) {
        return date.toISOString();
      } else {
        let dif = tzo >= 0 ? "+" : "-";
        let pad = function (num, digits = 2) {
          return String(num).padStart(digits, "0");
        };
    
        return (
          date.getFullYear() +
          "-" +
          pad(date.getMonth() + 1) +
          "-" +
          pad(date.getDate()) +
          "T" +
          pad(date.getHours()) +
          ":" +
          pad(date.getMinutes()) +
          ":" +
          pad(date.getSeconds()) +
          dif +
          pad(tzo / 60) +
          ":" +
          pad(tzo % 60) +
          "." +
          pad(date.getMilliseconds(), 3)
        );
      }
    }
    
    console.log(getISOLocalString());
    
  • The 6 ways of returning data from an Azure Function

    Why have one if you can have many? Well, beats me, but I thought I’d collect them here so I have my personal reference. Disclaimer: This is only for JavaScript based functions (most of the examples on the MS pages are C#).

    So, most of them have to do with the file function.json  file:

    {
      "bindings": [
        {
          "type": "httpTrigger",
          "name": "req",
          "and": "so on ..."
        },
        {
          "type": "http",
          "name": "thisIsAnOutputBinding",
          "direction": "out"
        },
        {
          "type": "someOtherType",
          "name": "anotherBinding",
          "direction": "out"
        }
      ]
    }
    

    More precisely, with the “out” type binding that is defined in the 2nd “bindings” object. The “out” binding has a “name” property, which is basically relevant for all of the methods.

    !!!!! WARNING !!!!! – It seems the name of the binding property must be camelCase**. At least I consistently get “invalid binding” errors when I use snake_case**

    Method 1 – context property

    The context object has one property per defined “out” binding. So if our property is named “thisIsAnOutputBinding”, our result property is context.thisIsAnOutputBinding , or as MicroSoft puts it:

    Outputs (bindings of direction === "out" ) can be written to by a function in a number of ways. In all cases, the name property of the binding as defined in function.json corresponds to the name of the object member written to in your function.

    Simply put, you just assign the value to a context  member and you’re done:

    module.exports = function (context, req) {
      context.thisIsAnOutputBinding = {
        my: "return value",
        "in this case": "an object",
      };
      // contect.done() is only needed for synchronous functions context.done();
    };
    

    Source here.

    Method 2 – return an object (async functions only)

    With the bindings given above, you can assign the values to the context property, but you can also return an object whose keys correspond to the binding names:

    module.exports = async function (context) {
      return { thisIsAnOutputBinding: 42, anotherBinding: 43 };
      // of course, instead of 42/43 you can put any js object here.
    };
    

    Source here.

    Method 3 – using context.bindings

    This is basically a variant of method 1. Why does it exist? No one knows. Apparently the context object has a .bindings  property, which in turn again has properties which name-match the defined out bindings. So this is another possibility, and I think the return  is unnecessary:

    module.exports = async function (context) {
      let retMsg = "Hello, world!";
      context.bindings.thisIsAnOutputBinding = {
        body: retMsg,
      };
      context.bindings.anotherBinding = retMsg;
      return;
    };
    

    Source here.

    Method 4 – using context.done()

    If you’re using a sync method, you can’t return an object, but you can call context.done(err, obj) .

    module.exports = async function (context) {
      context.done(null, {
        thisIsAnOutputBinding: { text: "hello there, world", anotherBinding: 42 },
      });
    };
    

    Source here.

    Method 5 – just return it already (only async functions)

    Probably someone said “Well, if I only have one output binding, why should I explicitly address it?”, which is a valid thought. So another way to return data was invented.

    For this the configuration in function.json looks a bit different:

    {
      "bindings": [
        { "type": "someType", "name": "req", "direction": "in" },
        { "type": "someOutType", "direction": "out", "name": "$return" }
      ]
    }
    

    You have to set exactly one “out” type binding, and the name must be “$return”. Then you can do this:

    module.exports = async function (context, req) {
      return "woohooo!!";
    };
    

    Source here.

    Methods 6 – special for http outputs

    You thought we were done? Noooooo. For http methods, you can diretly return the body object which is then used to create the body

    // actually NO IDEA if this works sync, async or both
    // my guess is: sync, because "context.done() is implicitly called"
    module.exports = async function (context, req) {
      rv = { body: "<html/>", status: 201 };
      context.res.send(rv);
    };
    

    Source here.

    Summary

    Let’s just say it’s a mess, and too many ways ruin the map.

    It works though.

  • Microsoft Code and Typescript

    So being on the enterJS conference I wanted to get started with JavaScript. And TypeScript seems really promising. And once again I stumbled over the DIW pattern – Download, Install, Weird error messages.

    So, here’s my take on how to get started.

    I wanted …

    • to try node-hid to see my USB HID devices, using TypeScript, Microsoft Visual Studio Code, and Node.js.

    So here’s how to get it to work:

    $ mkdir my_project_dir
    $ cd my_project_dir
    $ brew install node            # I'm on Mac ;)
    $ npm install -g typescript    # install globally
    $ npm install node-hid         # install locally
    

    Fire up Code, and “open” the project directory “my_project_dir”.

    Press “CMD-SHIFT-P” (probably CTRL-SHIFT on non-OSX machines) and search for “Configure task runner”. Here you use this configuration:

    {
      "version": "0.1.0",
      "command": "tsc",
      "isShellCommand": true,
      "showOutput": "silent",
      "args": [],
      "problemMatcher": "$tsc"
    }
    

    Then create a new file called “test.ts”, with the following content:

    // typescript does not know "require".
    // you have to convince it it "will exist at runtime".
    // http://stackoverflow.com/a/12742371/902327
    declare function require(name: string);
    var HID = require("node-hid");
    var devices = HID.devices();
    console.log(devices);
    

    Now if you press “CMD-SHIFT-B” this should compile and create a file called “test.js”.

    I don’t know (yet) how to run it from within Code, so on the command line I can test it by doing …

    // command: node test.js
     { vendorId: 1452,
        productId: 589,
        path: 'USB_05ac_024d_fa120000',
        serialNumber: '',
        manufacturer: 'Apple Inc.',
        product: 'Apple Internal Keyboard / Trackpad',
        release: 521,
        interface: -1 },
      { vendorId: 0,
        productId: 0,
        path: '',
        serialNumber: '',
        manufacturer: '',
        product: 'Apple Mikey HID Driver',
        release: 0,
        interface: -1 },
      { vendorId: 1452,
        productId: 589,
        path: 'USB_05ac_024d_fa120000',
        serialNumber: '',
        manufacturer: 'Apple Inc.',
        product: 'Apple Internal Keyboard / Trackpad',
        release: 521,
        interface: -1 },
      { vendorId: 1452,
        productId: 589,
        path: 'USB_05ac_024d_fa120000',
        serialNumber: '',
        manufacturer: 'Apple Inc.',
        product: 'Apple Internal Keyboard / Trackpad',
        release: 521,
        interface: -1 },
      { vendorId: 1452,
        productId: 589,
        path: 'USB_05ac_024d_fa120000',
        serialNumber: '',
        manufacturer: 'Apple Inc.',
        product: 'Apple Internal Keyboard / Trackpad',
        release: 521,
        interface: -1 } ]
    

    Article Sources:

    Microsoft Visual Studio Help Stackoverflow