如何使用Node.js解析OneNote文件?Microsoft Graph API使用遇阻
解决Node.js解析OneNote文件的两个问题
一、用Microsoft Graph API定位并解析OneNote文件
OneNote文件(.one/.onepkg)存储在OneDrive或SharePoint中,Graph API需先通过Drive接口定位文件,再获取内容:
- 搜索OneDrive中的OneNote文件
调用Drive搜索接口,筛选扩展名.one或.onepkg的文件:const { Client } = require('@microsoft/microsoft-graph-client'); const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials'); const { ClientSecretCredential } = require('@azure/identity'); // 初始化Graph客户端 const credential = new ClientSecretCredential( 'tenant-id', 'client-id', 'client-secret' ); const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: ['https://graph.microsoft.com/.default'] }); const client = Client.initWithMiddleware({ authProvider }); // 搜索OneNote文件 async function findOneNoteFiles() { const response = await client.api('/me/drive/root/search(q=\'.one\')') .select('id,name,webUrl') .get(); return response.value; } - 根据文件ID获取OneNote内容
拿到文件ID后,调用内容导出接口获取原始内容,若为.onepkg需先解压,.one文件可搭配社区解析库处理:async function getOneNoteContent(fileId) { const content = await client.api(`/me/drive/items/${fileId}/content`) .responseType('arraybuffer') .get(); return content; }
二、解决“onenote模块不存在”的报错
你调用的onenote.run是Office.js浏览器端API,仅能在Office插件环境使用,Node.js环境无此模块。Node.js中操作OneNote有两种方案:
- 使用Microsoft Graph Node.js SDK:如上述示例的
@microsoft/microsoft-graph-client包,通过REST API与云端OneNote交互 - 本地文件解析:用社区维护的
onenote-parser库(先执行npm install onenote-parser安装),示例:const { parseOneNote } = require('onenote-parser'); const fs = require('fs'); async function parseLocalOneNote(filePath) { const buffer = fs.readFileSync(filePath); const note = await parseOneNote(buffer); console.log(note.pages); // 输出页面内容结构 }
内容的提问来源于stack exchange,提问作者Aswath
相关产品推荐
相关产品推荐

