Node.js _dirname & path All In One
file path
相对路径
绝对路径
_dirname
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
__filename
Running node example.js from /Users/mjr
console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr
path
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
- Express.js / Koa.js
- React SSR
- Vue SSR
- Electron app
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-11-01
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
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({
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()
}
})
refs
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 发布文章使用:只允许注册用户才可以访问!