首页 > 解决方案 > 需要读取本地文件的 npm 包?

问题描述

我正在构建一个 ES 模块,该模块需要通过命令行在浏览器和 Node.js 中运行,并且它需要读取包含包中数据的文件。想象一个英语词典包,其中english_words.txt有一个常规单词列表,index.js看起来像这样

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url)) // There's no __dirname in ES modules
const dictionaryFile = path.resolve(__dirname, 'english_words.txt')
const englishWords = fs.readFileSync(dictionaryFile).split('\n')

export const isEnglishWord = word => englishWords.includes(word)

我的问题是我不知道如何以在浏览器中也可以工作的方式读取 txt 文件。如果有人将我的包与 JS 构建器/捆绑器一起使用,那将如何工作?

标签: javascriptnode.jsnpm

解决方案


推荐阅读