1

我在 typescript 中创建了一个小型 CLI 工具,并已实现使用 nexe 从中创建一个 .exe。一个新的用例是写出一些捆绑在应用程序中的文件:假设我的 CLI 工具为用户提供了空模板文件,然后用户可以填写这些文件。

一个示例命令是:myapp.exe --action export-templates --outdir path/to/some/dir

现在应该发生的是 CLI 工具会将其包含的模板文件导出到此位置。

我已经捆绑了这些文件,请参阅我的 package.json 的摘录:

"scripts": {
    "build": "npm run compile && nexe compiled/index.js --target windows-x64-10.16.0 --resource \"resources/**/*\""
  }

我尝试使用以下方式访问文件:

const fileBuffer = fs.readFileSync(path.join('__dirname', `/templates/mytemplate.doc`));

但是,我想出了一个例外: Error: ENOENT: no such file or directory, open 'C:\Users\Tom\compiled\templates\mytemplate.doc'

谁能告诉我如何使用 fs 正确访问捆绑的 .exe 中的文件?

4

1 回答 1

0

好吧,太糟糕了,我需要自己找到这个,文档在这方面真的不是很好......

在偶然发现 2016 年和 2017 年(主要是https://github.com/nexe/nexe/pull/93)的一些问题之后,我认为解决方案是使用nexeres. 好吧,事实证明这可能曾经起作用,但肯定不再起作用了。在我的应用程序中添加 arequire('nexeres')时,它会遇到Error: Cannot find module 'nexeres'错误。

所以我再次搜索问题,最后在https://github.com/nexe/nexe/issues/291中找到了解决方案:只需使用fs.readFilefs.readFileSync使用相对路径。我的最终代码如下所示:

// iterate over all files in the 'templates' folder INSIDE the .exe
each(fs.readdirSync('templates'), (filename: string) => {
  const dataBuffer = fs.readFileSync(`templates/${filename}`);
  // do sth with that file data, e.g. export it to some location (outside the .exe)
  const stream = fs.createWriteStream(`${outDir}/${filename}`);
  stream.write(dataBuffer );
  stream.close();
});
于 2020-08-27T09:23:30.597 回答