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. Eg:
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 `
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.