首页 > 解决方案 > Node.js ReadStream 在管道到 Hash 时卡在 Electron 上

问题描述

我正在使用vue-clivue-cli-plugin-electron-builder创建这个应用程序,我遇到了这个奇怪的问题,特定于电子,一旦应用程序启动,第一个ReadStream创建的应用程序不会将其内容通过管道传输到给定的流。

现在,通过刷新应用程序CTRL + F5将使流再次工作,从此不再有任何问题。

我当前的代码类似于应用程序启动后在渲染线程上调用:

public async run() {
  await this.scanFolder("/some/path/to/a/folder");
}

private async scanFolder(path: string){
  const entries = readdirSync(path, { withFileTypes: true });

  for (const entry of entries){
    if (!entry.isDirectory()){
      const md5 = await calculateMD5(path + "/" + entry.name);
    }
  }
}

public static async calculateFileMD5(path: string) {
  const md5 = createHash("md5");
  md5.setEncoding("hex");

  console.log("Creating promise");
  const promise = new Promise<string>((resolve, reject) => {
    const fileStream = createReadStream(path, {
      autoClose: true,
      emitClose: true
    });

    fileStream.on("open", () => console.log("STREAM OPEN"));
    fileStream.on("ready", () => console.log("STREAM READY"));
    fileStream.on("close", () => {
      console.log("Stream closed");
      resolve(md5.read());
    });

    fileStream.on("data", data => {
      console.log(data);
    });

    fileStream.on("end", () => {
      console.log("Stream ENDED");
      resolve(md5.read());
    });

    fileStream.on("error", error => {
      console.error(error);
      reject(error);
    });

    console.log("Piping to MD5");
    fileStream.pipe(md5, { end: true });
    fileStream.resume();
    console.log("Is paused?: " + fileStream.isPaused());
  });
  console.log("Returning promise");
  return promise;
}

启动应用程序npm run electron:serve并调用该run函数将输出以下内容:

Creating promise
Piping to MD5
Is paused?: false
Returning promise
STREAM OPEN
STREAM READY

现在,如果通过CRTL + F5流重新加载应用程序,则将其内容正确地通过管道传递给 Hash。

一旦应用程序启动以使流正常工作,我能做些什么使它不需要刷新?

标签: javascriptnode.jsvue.jselectron

解决方案


推荐阅读