我想将 .url 文件的文件夹导入到 Safari 中,但 Safari 只支持 HTML 书签文件。我怎样才能进行这种转换?
我编写了这个 TS 脚本来获取 .url 文件的 URL 和标题,并将它们转换为 bookmarks.html 文件。
async function createHtmlFileFromDiskBookmarks() {
const list = await fs.readdir("bookmarks_to_import");
const urlLines = await resolveInOrder<string, string>(
list,
async (filename) => {
const contents = await fs.readFile(`bookmarks_to_import/${filename}`, {
encoding: "utf-8",
});
const urlLine =
contents.split("\n").find((l) => l.startsWith("URL=")) ?? no();
const url = urlLine.slice(4);
const title = filename.slice(0, -4);
return `<dt><a href="${url}">${title}</a></dt>`;
},
);
const fileContent = `<title>Bookmarks</title>
<h1>Bookmarks</h1><dl><p>${urlLines.join("\n")}</p></dl>`;
await fs.writeFile("All bookmarks.html", fileContent);
console.log("done!");
}
// Generic helpers:
export async function resolveInOrder<V, R>(
inputs: V[],
callback: (element: V, index: number, previousResults: R[]) => Promise<R>,
): Promise<R[]> {
return inputs.reduce<Promise<R[]>>(
async (accArrPromise, val, i) => {
const prevResults = await accArrPromise;
const currResult = await callback(val, i, prevResults);
return [...prevResults, currResult];
},
Promise.resolve([]),
);
}
export function no(message?: string): never {
const assertionMessage = `no() called: ${message ?? "No message"}`;
console.error(assertionMessage);
throw new Error(assertionMessage);
}