Skip to content

Instantly share code, notes, and snippets.

@gwpantazes
Created November 17, 2022 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwpantazes/6f3306469dce21f9cc150c78f5890b4a to your computer and use it in GitHub Desktop.
Save gwpantazes/6f3306469dce21f9cc150c78f5890b4a to your computer and use it in GitHub Desktop.
Half-baked solution to Open in Editor in Node.js like git commit does (Forsaken in favor of Inquirer Prompt type 'Editor')
import { spawnSync } from 'child_process'
import { readFileSync } from 'fs'
import { temporaryWriteSync } from 'tempy'
// Get the default editor
const editor = process.env['VISUAL'] || process.env['EDITOR'] || 'vi'
console.log(`Opening in EDITOR: ${editor}. Save and quit the editor process to continue.`)
// If within another interactive program, uncomment this to prevent wacky visuals
// console.clear()
// Create a temp file
const preloadedFileContents = 'hello world'
const tempFileName = temporaryWriteSync(preloadedFileContents)
// Open the Editor Process - Wait until process exits.
spawnSync(editor, [tempFileName], {stdio: 'inherit'});
// Once process has exited, read the file contents
const fileContents = readFileSync(tempFileName, { encoding: 'utf-8' }).trim()
// Cleanup if necessary, depending on what you're doing
const lines = fileContents.split('\n')
.map(it => it.trim())
.filter(it => !/^\s*$/.test(it))
@gwpantazes
Copy link
Author

gwpantazes commented Nov 17, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment