如何在 nodejs 上创建文件实例

分享于2022年07月17日 fs node.js 问答
【问题标题】:如何在 nodejs 上创建文件实例(How can I create File Instance on nodejs)
【发布时间】:2022-01-26 12:10:42
【问题描述】:

我需要 Nodejs 上的 File 实例。我有文件路径,但我的主要函数接受 File 实例。如何从文件路径中获取 File 实例?

// I need a function like that, but it throws an error like `File is not defined`

const fs = require('fs');
const path = require('path');

/**
 * @param {string} filepath
 * @returns {File} 
 */
function getFileFromPath(filepath) {
  const buffer = fs.readFileSync(filepath);
  return new File(buffer, path.basename(filepath));
}



  • node.js 中没有“文件实例”。你想要什么?听起来像是 xy 问题。

【解决方案1】:

我认为你暗示了 FileHandle 的概念。

FileHandle 对象是数字文件的对象包装器 描述符。

Detail

代码:

const fs = require('fs');
const path = require('path');

/**
 * @param {string} filepath
 * @returns {FileHandle} 
 */
async function getFileFromPath(filepath) {
  const fileHandle = await fs.promises.open(filepath,'r');
  return fileHandle;
}

  • 这不是我想要的。