In case you are searching for JXA version:
Reusable class
class iTerm {
constructor() {
this.app = Application("iTerm");
this.window = this.app.currentWindow();
}
findOrCreateTab(tabName, command) {
this.app.activate();
let existingTab = this.findTab(tabName);
if (existingTab == undefined) {
existingTab = this.createTab(tabName);
console.log(`Created new tab: ${tabName}`);
existingTab.currentSession().write({ text: command });
} else {
existingTab.select();
console.log(`Found existing tab: ${tabName}`);
}
return existingTab;
}
createTab(name) {
const newTab = this.window.createTabWithDefaultProfile();
const session = newTab.currentSession();
session.name = name;
// console.log(newTab.index());
// console.log(newSession.name());
// console.log(newSession.profileName());
return newTab;
}
findTab(name) {
const tabs = this.window.tabs();
for (const tab of tabs) {
let session = tab.currentSession();
// Strange, but iTerm uses `profileName` instead of `name` for keeping manually assigned session name.
const tabName = session.profileName();
if (tabName === name) {
return tab;
}
}
return undefined;
}
}
In case you are also interesting how to use ESM modules in JXA (via browserify), then here is a good example: https://github.com/johnelm/node-jxa. Plus https://www.npmjs.com/package/esmify.
After setting up you can import reusable class as show below:
import iTerm from "../lib/iTerm";
const app = new iTerm();
app.findOrCreateTab("MyTab", `cd "$HOME"`);
open -a iTerm
to run a command.