diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Postman Automatic Auth Token

Postman can run JavaScript commands when executing a request. These commands can be placed in the "Tests" tab inside a request. For example, to automatically set a token as a collection variable, the following commands are used:

var auth = pm.response.headers.get("Authorization");
pm.collectionVariables.set('token', auth.split(" ")[1]);

The Docs regarding Postman scripting can be found here:

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/

Using destructuring assignment to dynamically create new functions in JavaScript

// www.codewars.com/kata/525f3eda17c7cd9f9e000b39

const curry = (operand, operator) => (!operator) ? operand : operator(operand);

const [zero, one, two, three, four, five, six, seven, eight, nine] =
  [0,1,2,3,4,5,6,7,8,9].map(operand => ((operator) => curry(operand, operator)));

const plus = (first) => (second) => second + first;
const minus = (first) => (second) => second - first;
const times = (first) => (second) => second * first;
const dividedBy = (first) => (second) => Math.floor(second / first);

Write to file with JavaScript and Node.js

Sometimes, as a programmer, you might need to write something to a file on the local file system. And that can be a piece of cake, case in which you'll use your favorite text editor to do it manually, but other times, it needs to be something complex and dynamic and you want your JavaScript to do it for you.

Here's how:

We'll first require the fs module from Node.js into our JS file.

const fs = require('fs');

Then we'll grab our content:

const content = 'Hello World!';

And finally we'll use the writeFile function from the fs module to populate our file. We need to provide the name of our file, the data or content to populate it with, the options (optional - for encoding, modes or flags) and a callback (also optional - to show the error message should one arise).

fs.writeFile(filename, data, [options], [callback]);

Here I've given it the a+ flag - "Open file for reading and appending. The file is created if it does not exist.". The encoding defaults to 'utf8' if none is given.

fs.writeFile('file.txt', content, { flag: 'a+' }, (err) => {
  if (err) throw err;
});