美文网首页
node中的方法

node中的方法

作者: 如果俞天阳会飞 | 来源:发表于2023-07-30 17:09 被阅读0次

url

url.fileURLToPath(url)

  • url <URL> | <string> 要转换为路径的文件网址字符串或网址对象
  • 返回: <string> 完全解析的特定于平台的 Node.js 文件路径
import { URL, fileURLToPath} from 'url';

// 将文件转换为路径
export const packagePath = fileURLToPath(new URL('../package.json', import.meta.url).href);


 console.log(new URL('../package.json', import.meta.url));
 console.log(packagePath); 
image.png

url.pathToFileURL(path)

  • path <string> 要转换为文件网址的路径。
  • 返回: <URL> 文件网址对象
import { pathToFileURL } from 'node:url';

async function getFile() {
  const cwd = process.cwd();

  const configPath = join(cwd,'config.js')

   console.log(1,configPath)
   console.log(2,pathToFileURL(configPath).href)
  return await import (pathToFileURL(configPath).href)
}


 const file = await getFile();
 console.log(3,file, 'file')

// 1. 获取文件的路径
// 2. 根据路径转成 文件的url
// 3.根据文件url 获取文件里面的内容
image.png

相关文章

网友评论

      本文标题:node中的方法

      本文链接:https://www.haomeiwen.com/subject/wwyspdtx.html