2016-11-21 113 views
3

如何在节点webkit应用程序中获取目录(而不是当前工作目录)的绝对路径?获取节点webkit中目录的完整路径

示例(Mac OS) - 我在我的Documents中创建了一个名为A的文件夹。当我做getDirectory与文件系统的目录项,我只能得到dir.fullPath返回A

app.workspace.getDirectory(self.folderpath, {}, function(dir){ 
    if(dir) console.log('Dir: ', dir); 
}); 

但我需要:~/Documents/A/ || c:\Users\Username\Documents

在我的应用程序中,用户可以选择/创建一个他们想要的目录,并且从该文件夹存储/读取数据。

绝对路径可能不是我所需要的,但我想用默认的桌面应用程序打开文件(PDF,DOC ...):

function getCommandLine() { 
    switch (process.platform) { 
     case 'darwin' : return 'open'; 
     case 'win32' : return 'start'; 
     case 'win64' : return 'start'; 
     default : return 'xdg-open'; 
    } 
} 

var exec = require('child_process').exec; 
var filepath = '...'; 
//dir.fullPath will throw: The file /A/example.pdf does not exist. 

var child = exec(getCommandLine() + ' ' + filepath, function (error, stdout, stderr) { 
    if (error) { 
     console.error(`exec error: ${error}`); 
      return; 
    } 
}); 
child.on('close', function (e) { 
    console.log('E: ', e); 
}); 

回答

0

其实我最近发现(我不相信我错过了它,但是),与铬文件系统,你可以得到“更可读”的路径信息用于显示目的。

取决于你正在尝试做的,你可能无法访问的绝对位置,但至少你可以看到它是什么...

fileSystem.getDirectory(path, {}, function(dir){ 
    if(dir) console.log('This should return full path: ', dir.getDisplayPath()); 
    var fullpath = dir.getDisplayPath(); 

    //now with this, I can open any file I want via child process :) 

    var child = exec(getCommandLine() + ' ' + fullpath, function (error, stdout, stderr) 
    //....... 
}); 

更多信息here关于铬的文件系统。

1

不知道我理解thequestion。您可以使用__dirname来获取正在执行的脚本的目录。请参阅:https://nodejs.org/docs/latest/api/globals.html#globals_dirname

并从那里您可以使用相对路径来引用其他文件和文件夹。

实施例的文件夹结构:

/home/filippo/works/test/ 
├── subfolder 
│   └── index.js 
└── test.js 

子目录/ index.js:

module.exports = {'folder': __dirname}; 

test.js:

var m = require("./subfolder/"); 

console.log("test.js running in: ", __dirname); 
console.log("m module running in: ", m.folder); 

运行测试:

$ node test.js 
test.js running in: /home/filippo/works/test 
m module running in: /home/filippo/works/test/subfolder 

这是你在找什么?

+0

是的,你还没有明白它:)脚本的目录和我想要访问的文件夹是分开的。两者可以在任何地方。该脚本显然是从应用程序包运行的,理想情况下应该位于Applications文件夹中,而其他目录是自由选择的。用户可以选择他们机器上任何位置的任何文件夹。我真正想要做的是用用户的默认应用程序打开文档,我发现一个这样做与exec执行的方式,但外壳脚本运行从根... –

+0

好的抱歉。而且你不能存储用户在某个地方选择的文件夹。 – filippo

+0

不是完整的网址否 - 它是沙盒。我在我的'〜/ Documents/Myfolder'中创建了我的文件夹..我只能返回'/ Myfolder' –

2

出于安全原因,您无法从网页访问系统目录文件的绝对路径。即使您尝试从JavaScript脚本访问特定文件目录(例如),浏览器也会立即阻止您。

可能适用于您的解决方案是通过简单的<input type="file">来检索用户想要打开的文件,以便用户可以选择文件而无需为您提供绝对路径;之后您可以保存该文件到服务器主机,甚至项目的本地目录,然后使用远程路径使用exec命令打开它。