Reputation: 923
Let's make clear once again: I don't need process.cwd
in this question, I need
to access to absolute path of source project. E.g:
C:\Users\user1\projects\lib1\src\library.ts
(becomes to Node Module in the future)C:\Users\user1\projects\someProject\src\someProject.ts
So, I need to get the C:\Users\user1\projects\lib1\src
inside library.ts
.
I tried:
webpack.config.js
module.exports = {
// ...
target: 'node',
externals: [nodeExternals()],
plugins: [
new Webpack.DefinePlugin({
__PROJECT_ROUTE_ABSOLUTE_PATH__: __dirname
})
]
};
project-types.d.ts
declare var __PROJECT_ROUTE_ABSOLUTE_PATH__: string;
If to try console.log(__PROJECT_ROUTE_ABSOLUTE_PATH__)
in library.ts
, below invalid JavaScript
will be produced:
console.log(C:\Users\user1\projects\lib1);
The path is correct, but quotations are missing. I don't know how to explain it. But anyway, how we can get right path?
There is also a strange phenomena: if to invoke __dirname
, just /
will be returned, so path.resolve(__dirname, 'fileName') gives
C:\fileName `
Upvotes: 1
Views: 544
Reputation: 1020
You can directly use the node.js path
module which is in built.
The path module provides utilities for working with file and directory paths. It can be accessed using:
const path = require('path');
__filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/user/some/dir/file.js)
__dirname is the directory name of the current module. (ex:/home/user/some/dir)
fs.readFile(path.resolve(__dirname + 'fileName'))
This will resolve to the path of the file.
Upvotes: 1