Skip to content

Instantly share code, notes, and snippets.

@tsmx
tsmx / nodejs-promise-basic-example.js
Last active November 11, 2020 20:10
NodeJS Promise example showing basic usage and control flow with: resolve, reject, then, catch & throw.
function isOdd(x) {
return new Promise((resolve, reject) => {
if (x == 11) throw new Error('11 is not allowed!');
if (x % 2) {
resolve(x.toString() + ' is odd')
}
else {
reject(new Error(x.toString() + ' is even'));
}
});
@tsmx
tsmx / got-download-stream.js
Last active October 6, 2022 13:40
Stream-download a file with filename from response header (content-disposition) via got package.
const got = require('got');
const stream = require('stream');
const fs = require('fs');
const { promisify } = require('util');
const pipeline = promisify(stream.pipeline);
// instantiate the download stream - use options to set authorization header etc. if needed
let downStream = got.stream('https://example.com/download');
downStream.on('response', response => {
@tsmx
tsmx / got-authorization-header.js
Last active August 2, 2022 13:43
Set authorization header with bearer-token in got.
const got = require('got');
// get 'url' and 'token'...
got.get(url), {
responseType: 'json',
hooks: {
beforeRequest: [
options => {
options.headers['Authorization'] = 'Bearer ' + token;
@hofnerb
hofnerb / remote_url.md
Last active October 16, 2023 05:43
git remote set-url

Review and Change Remote URL

git remote -v
# View existing remotes

git remote set-url origin https://github.com/user/repo2.git
# Change the 'origin' remote's URL

git remote -v
@kljensen
kljensen / mongoose-encrypted-schematype-field.md
Last active June 6, 2023 13:25
Encrypt a text field in Mongoose MongoDB ORM

Encrypting text fields in Mongoose is easy using Node's built-in crypto module. You might want to do this if you're using MongoDB as a service (see the recent MongoHQ security breach); or, if you're storing OAuth tokens that could, in the wrong hands, screw with somebody's account on a 3rd party service. (Of course, you should never encrypt passwords: those should be hashed.)

Imagine you have a Mongoose model like that shown below, which is modified only slighly from the example on the MongooseJS homepage.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var User = mongoose.model('User', {
 name: String,