我有一个应用程序,其结构如下所示:
.
├── index.js
├── unix
│ ├── index.js
└── win32
├── foo.exe
└── index.js
win32/index.js
正在访问 foo.exe
,如下所示:
let command = path.join(__dirname, "foo.exe") + ' -some-arguments';
exec(command);
但现在使用 Webpack,我将应用程序编译到一个 bundle.js 中,并将该 foo.exe
放在它旁边:
.
├── foo.exe
└── bundle.js
现在 path.join(__dirname, "foo.exe")
不再起作用。它找不到 foo.exe
。我已将其更改为
let command = path.resolve(
"node_modules/my-library/dist",
"foo.exe"
);
它工作得很好,但看起来有更好的方法。
更新:
我的 Webpack 配置文件:
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
mode: "production",
entry: "./src",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
libraryTarget: "umd"
},
plugins: [new CopyPlugin([{ from: "./src/win32/foo.exe" }])],
target: "node"
};
最佳答案
要让 __dirname
以通常的方式运行,并且不被 Webpack 更改( mock ),您必须在 Webpack 配置中添加一个属性:
module.exports = {
//...
node: {
__dirname: false,
}
};
关于javascript - 从 Node 应用程序获取文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57196632/