rel1x
rel1x

Reputation: 2441

Get a path to a file from Node application

I have an application, where structure looks like this:

.
├── index.js
├── unix
│   ├── index.js
└── win32
    ├── foo.exe
    └── index.js

win32/index.js was accessing foo.exe like this:

let command = path.join(__dirname, "foo.exe") + ' -some-arguments';
exec(command);

But now using Webpack I compile my application into one bundle.js and put that foo.exe next to it:

.
├── foo.exe
└── bundle.js

And now path.join(__dirname, "foo.exe") doesn't work anymore. It doesn't find the foo.exe. I've changed it to

  let command = path.resolve(
    "node_modules/my-library/dist",
    "foo.exe"
  );

And it works fine but looks like there is a better way to do it.

UPD:

my Webpack config file:

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"
};

Upvotes: 0

Views: 89

Answers (2)

Seblor
Seblor

Reputation: 7146

To have __dirname behave the usual way, and not being it changed (mocked) by Webpack, you have to add a property in your Webpack config :

module.exports = {
  //...
  node: {
    __dirname: false,
  }
};

Documentation

Upvotes: 2

Tien Duong
Tien Duong

Reputation: 2595

You need to add these node config in your webpack. So you can use __dirname after you built your code with webpack

  node: {
      __dirname: false,
    },

Upvotes: 1

Related Questions