Node.js _dirname & path All In One
阅读原文时间:2023年07月08日阅读:1

Node.js _dirname & path All In One

file path

相对路径

绝对路径

https://nodejs.org/docs/latest/api/globals.html#globals_dirname

https://nodejs.org/docs/latest/api/modules.html#modules_dirname

const log = console.log;

// log(`__dirname`, __dirname);

This is the same as the path.dirname() of the __filename.

Example: running node example.js from /Users/mjr

console.log(__dirname);
// Prints: /Users/mjr

console.log(path.dirname(__filename));
// Prints: /Users/mjr

Running node example.js from /Users/mjr

console.log(__filename);
// Prints: /Users/mjr/example.js

console.log(__dirname);
// Prints: /Users/mjr

https://nodejs.org/api/path.html

https://github.com/nodejs/node/blob/v15.2.0/lib/path.js

const log = console.log;

const path = require('path');

// path.dirname(file_path);

let directories = path.dirname('/Users/xgqfrms/app.js');

log(directories);
// /Users/xgqfrms
  1. Express.js / Koa.js

  2. React SSR

  3. Vue SSR

  4. Electron app

    "use strict";

    /**
    *

    const log = console.log;

    const path = require('path');
    // path.dirname(file_path);

    // log(__dirname, __dirname);

    const { app, BrowserWindow } = require('electron')

    function createWindow () {
    const win = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
    nodeIntegration: true
    }
    })

    // win.loadFile('index.html');
    // win.loadFile(__dirname + '/index.html');
    // relative path 拼接
    // win.loadFile(__dirname.replace(src, ) + '/public/index.html'); let directories = path.dirname('index.js'); log(`directories =`, directories); // directories = ., . 即指项目的 root path // win.loadFile(directories.replace(`src`,) + '/public/index.html');
    win.loadFile('./public/index.html');
    // 打开 debug 模式
    win.webContents.openDevTools();
    }

    app.whenReady().then(createWindow)

    app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
    app.quit()
    }
    })

    app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
    }
    })

https://stackoverflow.com/questions/8131344/what-is-the-difference-between-dirname-and-in-node-js

difference between __dirname and ./ in Node.js

https://www.geeksforgeeks.org/difference-between-__dirname-and-in-node-js/

https://www.w3schools.com/nodejs/met_path_dirname.asp

process.cwd()

https://coderrocketfuel.com/article/get-the-path-of-the-current-working-directory-in-node-js



xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章