2 * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
3 * Copyright (c) 2016, Daniel Imms (MIT License).
4 * Copyright (c) 2018, Microsoft Corporation (MIT License).
8 #include <Shlwapi.h> // PathCombine
10 #include "path_util.h"
14 const wchar_t* to_wstring(const Nan::Utf8String& str) {
15 const char *bytes = *str;
16 unsigned int sizeOfStr = MultiByteToWideChar(CP_UTF8, 0, bytes, -1, NULL, 0);
17 wchar_t *output = new wchar_t[sizeOfStr];
18 MultiByteToWideChar(CP_UTF8, 0, bytes, -1, output, sizeOfStr);
22 bool file_exists(std::wstring filename) {
23 DWORD attr = ::GetFileAttributesW(filename.c_str());
24 if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
30 // cmd.exe -> C:\Windows\system32\cmd.exe
31 std::wstring get_shell_path(std::wstring filename) {
32 std::wstring shellpath;
34 if (file_exists(filename)) {
38 wchar_t buffer_[MAX_ENV];
39 int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
44 std::wstring delimiter = L";";
46 std::vector<std::wstring> paths;
47 std::wstring buffer(buffer_);
48 while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
49 paths.push_back(buffer.substr(0, pos));
50 buffer.erase(0, pos + delimiter.length());
53 const wchar_t *filename_ = filename.c_str();
55 for (int i = 0; i < paths.size(); ++i) {
56 std::wstring path = paths[i];
57 wchar_t searchPath[MAX_PATH];
58 ::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
60 if (searchPath == NULL) {
64 if (file_exists(searchPath)) {
65 shellpath = searchPath;
73 } // namespace path_util