Skip to content

Instantly share code, notes, and snippets.

@aadimator
Created August 20, 2022 05:05
Show Gist options
  • Save aadimator/efeff71acfd0f8172ed4e1a5c63da8dc to your computer and use it in GitHub Desktop.
Save aadimator/efeff71acfd0f8172ed4e1a5c63da8dc to your computer and use it in GitHub Desktop.
Add id (nanoid) YAML property to all .md files
import { nanoid } from 'nanoid';
import {globby} from 'globby';
import matter from 'gray-matter';
import { writeFile } from 'fs';
const NOTES_DIR = "../notes_temp"
const paths = await globby(NOTES_DIR, {
expandDirectories: {
extensions: ['md']
}
});
for (let path of paths) {
console.log(`\nProcessing: ${path}`);
const file = matter.read(path);
const metadata = file.data;
if (!metadata.hasOwnProperty('id')) {
// Use Raw Metadata so the order of the YAML properties remains the same
const raw_meta = file.matter.split('\n');
// The first entry is always an empty string. Replacing that with the ID
raw_meta[0] = `id: ${nanoid()}`
// Data to write to the file
const data = ['---', raw_meta.join('\n'), '---', file.content]
writeFile(path, data.join('\n'), function (err) {
if (err) return console.log(err);
console.log(`Updated: ${path}`);
});
}
}
{
"name": "notes_nanoid_generator",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"globby": "^13.1.2",
"gray-matter": "^4.0.3",
"nanoid": "^4.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment