我正在编写一个Visual Studio Code扩展,它使用工作区文件夹路径(File > Open Folder)来确定运行shell命令的基目录。我可以从vscode.workspace.workspaceFolders[0].uri.path
获取路径,但当我将其与fs.readdir()
一起使用时会出现问题,因为它在开头重复了驱动器号。
Error: ENOENT: no such file or directory, scandir 'C:\c:\Users\Dave\Desktop\ESP Labs'
- 注意额外的C:*
我想找到一种方法,将URI路径转换为适合fs.readdir()
的文件系统路径。我尝试了url.fileURLToPath()
,但它不起作用,实际上导致扩展停止工作,直到我注解掉console.debug行,我试图显示结果。
还有一个名为vscode.workspace.workspaceFolders[0].uri._fspath
的属性,这是我想要的,但我认为下划线表示该属性是私有的,不应该直接使用。
所以我的问题是
有没有一种方法可以将uri.path转换为文件系统路径,或者我应该忘记它而使用uri._fspath?
代码:
/*
* Copy entire project directory to remote flash file system.
*/
let syncCommand = vscode.commands.registerCommand('mpremote.sync', async () => {
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length != 1) {
vscode.window.showErrorMessage('Unable to sync. Open a folder first.')
}
else {
console.debug('vscode.workspace.workspaceFolders[0]', vscode.workspace.workspaceFolders[0])
console.debug('uri._fsPath:', vscode.workspace.workspaceFolders[0].uri._fsPath)
//console.debug('url.fileURLToPath:', url.fileURLToPath(vscode.workspace.workspaceFolders[0].uri.path))
let projectRoot = vscode.workspace.workspaceFolders[0].uri._fsPath
console.debug('Project folder path:', projectRoot)
let port = await getDevicePort()
term.sendText(`cd '${projectRoot}'`)
fs.readdir(projectRoot, { withFileTypes: true }, (err, entries) => {
if (err) {
console.error(err)
vscode.window.showErrorMessage('Unable to read directory.')
}
else {
console.debug('Directory entries found:', entries.length)
entries.forEach(entry => {
console.debug('Examining directory entry:', entry)
if (entry.isDirectory()) {
if (SYNC_IGNORE.includes(entry.name)) {
console.debug('Skipping directory:', entry.name)
}
else {
term.sendText(`${PYTHON_BIN} -m mpremote connect ${port} fs cp -r ${entry.name} :`)
}
}
else {
term.sendText(`${PYTHON_BIN} -m mpremote connect ${port} fs cp ${entry.name} :`)
}
})
}
})
}
})
显示可用uri属性的调试输出:
vscode.workspace.workspaceFolders[0] {uri: v, name: 'ESP Labs', index: 0}
vscode.workspace.workspaceFolders[0] {
uri: v {
scheme: 'file',
authority: '',
path: '/c:/Users/Dave/Desktop/ESP Labs',
query: '',
fragment: '',
_formatted: 'file:///c%3A/Users/Dave/Desktop/ESP%20Labs',
_fsPath: 'c:\\Users\\Dave\\Desktop\\ESP Labs'
},
name: 'ESP Labs',
index: 0
}
uri._fsPath: c:\Users\Dave\Desktop\ESP Labs
Project folder path: c:\Users\Dave\Desktop\ESP Labs
1条答案
按热度按时间nwlqm0z11#
您可以使用一个
vscode.workspace.workspaceFolders[0].uri.fsPath
属性-注意不要使用下划线。它返回与_fsPath
属性相同的内容。参见vscode API文档:尤里