如何在Node.js中使用__dirname

The double underscores in __dirname looks intimidating but it’s not! It’s a useful variable that’s been around since the beginnging of the NodeJS project. Why’s it such a core feature of Node.js? __dirname tells you the absolute path of the directory containing the currently executing file.

__dirname的双下划线看起来令人生畏,但事实并非如此! 自从NodeJS项目开始以来,这是一个有用的变量。 为什么它具有Node.js的核心功能? __dirname告诉您包含当前执行文件的目录的绝对路径 。

Here’s a simple example:

这是一个简单的例子:

gator-app
  ├──index.js
  ├──public
  ├──src
  │  ├──helpers.js
  │  └──api
  │      └──crocodile.js
  ├──cronjobs
  │  ├──swamp-pix
  │  └──get-latest-gators.js
  └──package.json
crocodile.js
crocodile.js
console.log(__dirname)      // "/Users/Sam/gator-app/src/api"
console.log(process.cwd())  // "/Users/Sam/gator-app"
get-latest-gators.js
get-latest-gators.js
console.log(__dirname)     // "/Users/Sam/gator-app/cronjobs"
console.log(process.cwd()) // "/Users/Sam/gator-app"

If you noticed, __dirname has a different value depending on which file you invoked it in, whereas process.cwd() (another popular Node.js utility) is different. It always returns the same value: the absolute path of where you started the Node.js process (eg., $ node index.js).

如果您注意到了, __dirname根据在哪个文件中调用它而具有不同的值,而process.cwd() (另一个流行的Node.js实用程序)则不同。 它始终返回相同的值: 在其中启动Node.js进程的绝对路径(例如$ node index.js ) 。

我什么时候应该使用它? (When Should I Use It?)

__dirname is useful when you want to know the immediate containing folder. You may want to get this path for several reasons:

当您想知道直接包含的文件夹时, __dirname很有用。 您可能出于以下几个原因而希望获得此路径:

制作新目录 (Making new directories)

get-latest-gators.js
get-latest-gators.js
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/swamp-pix');

fs.mkdirSync(dirPath); // sibling directory was created named "swamp-pix"

指向目录 (Pointing to directories)

index.js
index.js
express.static(path.join(__dirname, '/public'));

将文件添加到目录 (Adding files to a directory)

get-latest-gators.js
get-latest-gators.js
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/swamp-pix/bayou.jpeg');

fs.openSync(filePath, 'a'); // creates file if it doesn't exist

Once you get familiar with Node.js, interacting with your filesystem is easy when you use __dirname.

一旦熟悉Node.js,使用__dirname轻松与文件系统进行交互。

Plus, __dirname is a global object that’s available to use in all your Node.js modules, without having to import anything. That’s because Node modules get wrapped when executed and given access to a series of global objects.

另外, __dirname是一个全局对象,可以在所有Node.js模块中使用,而无需导入任何内容。 这是因为Node模块在执行并获得对一系列全局对象的访问权时会被包装

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
export default ({ command, mode }) => { const NODE_ENV = process.env.NODE_ENV || 'development' const envFiles = [ .env.${NODE_ENV} ] for (const file of envFiles) { const envConfig = dotenv.parse(fs.readFileSync(file)) for (const k in envConfig) { process.env[k] = envConfig[k] } } viteLogo(process.env) const timestamp = Date.parse(new Date()) const optimizeDeps = {} const alias = { '@': path.resolve(__dirname, './src'), 'vue$': 'vue/dist/vue.runtime.esm-bundler.js', } const esbuild = {} const config = { base: './', // index.html文件所在位置 root: './', // js导入的资源路径,src resolve: { alias, }, define: { 'process.env': {} }, server: { // 如果使用docker-compose开发模式,设置为false open: true, port: process.env.VITE_CLI_PORT, proxy: { // 把key的路径代理到target位置 // detail: https://cli.vuejs.org/config/#devserver-proxy [process.env.VITE_BASE_API]: { // 需要代理的路径 例如 '/api' target: `${process.env.VITE_BASE_PATH}/`, // 代理到 目标路径 changeOrigin: true, rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_API), ''), }, [process.env.VITE_BASE_EXPORT_API]: { // 需要代理的路径 例如 '/api' target: `${process.env.VITE_BASE_REPORTAPI}/`, // 代理到 目标路径 changeOrigin: true, rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_EXPORT_API), ''), }, }, }, build: { target: 'es2017', minify: 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser manifest: false, // 是否产出manifest.json sourcemap: false, // 是否产出sourcemap.json outDir: 'dist', // 产出目录 // rollupOptions, }, 使用vite部署时,请帮我修改以上代码,当build打包时,前端页面url新增VITE_PUBLIC_PATH= '/devOnlineStatus/'前缀
07-15
export default ({ command, mode }) => { const NODE_ENV = process.env.NODE_ENV || 'development' const envFiles = [ `.env.${NODE_ENV}` ] for (const file of envFiles) { const envConfig = dotenv.parse(fs.readFileSync(file)) for (const k in envConfig) { process.env[k] = envConfig[k] } } viteLogo(process.env) const timestamp = Date.parse(new Date()) const optimizeDeps = {} const alias = { '@': path.resolve(__dirname, './src'), 'vue$': 'vue/dist/vue.runtime.esm-bundler.js', } const esbuild = {} const config = { base: './', // index.html文件所在位置 root: './', // js导入的资源路径,src resolve: { alias, }, define: { 'process.env': {} }, server: { // 如果使用docker-compose开发模式,设置为false open: true, port: process.env.VITE_CLI_PORT, proxy: { // 把key的路径代理到target位置 // detail: https://cli.vuejs.org/config/#devserver-proxy [process.env.VITE_BASE_API]: { // 需要代理的路径 例如 '/api' target: `${process.env.VITE_BASE_PATH}/`, // 代理到 目标路径 changeOrigin: true, rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_API), ''), }, [process.env.VITE_BASE_EXPORT_API]: { // 需要代理的路径 例如 '/api' target: `${process.env.VITE_BASE_REPORTAPI}/`, // 代理到 目标路径 changeOrigin: true, rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_EXPORT_API), ''), }, }, }, build: { target: 'es2017', minify: 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser manifest: false, // 是否产出manifest.json sourcemap: false, // 是否产出sourcemap.json outDir: 'dist', // 产出目录 // rollupOptions, }, } // Add VITE_PUBLIC_PATH to the define object when building if (command === 'build') { config.define['process.env.VITE_PUBLIC_PATH'] = "'/devOnlineStatus/'" } return config }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值