xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js fs API _dirname & _filename & path All In One

Node.js fs API _dirname & _filename & 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

ESM & __dirname

模拟 CJS 默认的 __dirname

import fs from "fs";
import path from "path";

// 默认当前 root 路径 ✅
const __dirname = path.resolve();

https://www.cnblogs.com/xgqfrms/tag/path/

https://www.cnblogs.com/xgqfrms/p/16100047.html

https://www.cnblogs.com/xgqfrms/p/13983568.html

https://www.cnblogs.com/xgqfrms/p/16155641.html

demos

  1. Express.js / Koa.js

  1. React SSR

  1. Vue SSR

  1. 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({
    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()
  }
})


JSON to Markdown file convertor

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-06-01
 * @modified
 *
 * @description
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13983568.html
 * @link https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js/71735771#71735771
 * @link https://coderrocketfuel.com/article/get-the-path-of-the-current-working-directory-in-node-js
 * @link
 * @link https://nodejs.dev/en/learn/writing-files-with-nodejs/
 * @link https://nodejs.org/docs/latest/api/fs.html
 * @link https://stackoverflow.com/questions/2496710/writing-to-files-in-node-js
 *
 */

// import fs from "node:fs/promises";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from 'url';

import * as JSONObj from "./test.json" assert {type: "json"};

const log = console.log;

const __filename = fileURLToPath(import.meta.url);
const dir = path.dirname(__filename);
log(`__filename =`, __filename)
log(`dir =`, dir)

const arr = JSONObj.default;
for (const obj of arr) {
  const {Title: title, Body: body} = obj;
  const folder = path.resolve(path.join(dir), `blogs`);
  // const folder = path.resolve(`${path.join(dir)}/blogs`);
  if (!fs.existsSync(folder)) {
    fs.mkdirSync(folder);
  }
  const filename = path.resolve(`${folder}/${title}`);
  fs.writeFile(filename, body, err => {
    if (err) {
      log(`❌`, err)
    } else {
      log(`✅ filename =`, filename)
    }
  })
}

$ node ./app.mjs
__filename = /Users/xgqfrms-mm/Documents/github/cnblogs-backup/cnblogs-2023/json-to-markdown/app.mjs
dir = /Users/xgqfrms-mm/Documents/github/cnblogs-backup/cnblogs-2023/json-to-markdown
(node:27385) ExperimentalWarning: Importing JSON modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
✅ filename = /Users/xgqfrms-mm/Documents/github/cnblogs-backup/cnblogs-2023/json-to-markdown/blogs/爱因斯坦出的一道思考题,全球只有 2% 的人才可以解出!All In One
✅ filename = /Users/xgqfrms-mm/Documents/github/cnblogs-backup/cnblogs-2023/json-to-markdown/blogs/CSON vs JSON All In One
✅ filename = /Users/xgqfrms-mm/Documents/github/cnblogs-backup/cnblogs-2023/json-to-markdown/blogs/让你像黑客一样写代码(not really)All In One

image

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-06-01
 * @modified
 *
 * @description
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13983568.html
 * @link https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js/71735771#71735771
 * @link https://coderrocketfuel.com/article/get-the-path-of-the-current-working-directory-in-node-js
 * @link
 * @link https://nodejs.dev/en/learn/writing-files-with-nodejs/
 * @link https://nodejs.org/docs/latest/api/fs.html
 * @link https://stackoverflow.com/questions/2496710/writing-to-files-in-node-js
 *
 */

// import fs from "node:fs/promises";
import * as pfs from "node:fs/promises";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from 'url';

import * as JSONObj from "./test.json" assert {type: "json"};

const log = console.log;

const __filename = fileURLToPath(import.meta.url);
const dir = path.dirname(__filename);
log(`__filename =`, __filename)
log(`dir =`, dir)

const arr = JSONObj.default;
for (const obj of arr) {
  const {Title: title, Body: body} = obj;
  const folder = path.resolve(path.join(dir), `blogs`);
  // const folder = path.resolve(`${path.join(dir)}/blogs`);
  if (!fs.existsSync(folder)) {
    fs.mkdirSync(folder);
  }
  const filename = path.resolve(`${folder}/${title}.md`);
  fs.writeFile(filename, body, err => {
    if (err) {
      log(`❌`, err)
    } else {
      log(`✅ filename =`, filename)
    }
  })
}

async function test() {
  try {
    const filename = `${path.join(dir)}_promise.md`;
    await pfs.writeFile(filename, `promise version fs`)
    log(`✅ filename =`, filename)
  } catch (err) {
    log(`promise error ❌`, err)
  }
}

test();

https://github.com/xgqfrms/cnblogs-backup

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

node:fs/promises

declare module 'node:fs/promises' {
    export * from 'fs/promises';
}

/Users/xgqfrms-mm/Library/Caches/typescript/5.2/node_modules/@types/node/fs/promises.d.ts

https://github.com/xgqfrms/cnblogs-backup/issues/1#issuecomment-1597347777

https://gist.github.com/xgqfrms/1fd4330ce78fa279c9667c0284895d4a

node:fs

// fs alias 🎉
declare module 'node:fs' {
    export * from 'fs';
}

/Users/xgqfrms-mm/Library/Caches/typescript/5.2/node_modules/@types/node/fs.d.ts

"use strict";

/**
 * 
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-06-01
 * @modified 
 * 
 * @description 
 * @augments 
 * @example 
 * @link 
 * 
 */

// import fs from "node:fs/promises";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from 'url';

import * as JSONObj from "./test.json" assert {type: "json"};

const log = console.log;

// console.log(`JSONObj =`, JSONObj);
// console.log(`typeof JSONObj =`, typeof JSONObj);
// object
// console.log(`JSONObj.default =`, JSONObj.default);

const __filename = fileURLToPath(import.meta.url);
const dir = path.dirname(__filename);

log(`__filename =`, __filename)
log(`dir =`, dir)

const arr = JSONObj.default;
for (const obj of arr) {
    // log(`obj.Title =`, obj.Title)
    // log(`obj.Body =`, obj.Body)
    // fs.WriteStream(obj.Title)
    // fs.WriteStream(obj.Body)
}

https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js/71735771#71735771

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-2021

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

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-11-16 09:50  xgqfrms  阅读(172)  评论(8编辑  收藏  举报