Skip to content

Instantly share code, notes, and snippets.

View Siilwyn's full-sized avatar
🦀

Selwyn Siilwyn

🦀
View GitHub Profile
@odigity
odigity / knex.js
Last active February 2, 2021 14:34
Wrapping a unit test in a transaction for easy cleanup with Knex.js
#!/usr/bin/node
const Promise = require('bluebird')
const config = require('./config.json')
const knex = require('./lib/knex')(config.database).connection()
const mock = () => ({ user_id: Math.floor(Math.random() * 999) + 1, payload_type: 'foo', attributes: JSON.stringify({}) })
const before = (t) => {
@jkantr
jkantr / .md
Last active September 18, 2018 21:40
Fun with Express patterns

Express patterns

Parametric modules

This pattern takes advantage of lexical scope in javascript, CommonJS modules, and object destructuring. It's a good way to share stateful resources, such as a db connection object, to middleware and detached routers in Express.

Basic setup

/app.js:

const express = require('express')
@bisubus
bisubus / ES5-ES6-ES2017-ES2019 omit & pick
Last active April 13, 2024 21:03
ES5/ES6/ES2017/ES2019 omit & pick
@joepie91
joepie91 / 00_warning.md
Last active October 5, 2023 21:24
Asynchronous fs.exists

Important warning

You should almost never actually use this. The same applies to fs.stat (when used for checking existence).

Checking whether a file exists before doing something with it, can lead to race conditions in your application. Race conditions are extremely hard to debug and, depending on where they occur, they can lead to data loss or security holes. Using the synchronous versions will not fix this.

Generally, just do what you want to do, and handle the error if it doesn't work. This is much safer.

  • If you want to check whether a file exists, before reading it: just try to open the file, and handle the ENOENT error when it doesn't exist.
  • If you want to make sure a file doesn't exist, before writing to it: open the file using an exclusive mode, eg. wx or ax, and handle the error when the file already exists.