yao-pkg / pkg

Package your Node.js project into an executable
https://www.npmjs.com/package/@yao-pkg/pkg
MIT License
312 stars 11 forks source link

child_process.fork doesn't work #70

Open cage1618 opened 2 months ago

cage1618 commented 2 months ago

What version of pkg are you using?

5.11.12

What version of Node.js are you using?

20.11.1

What operating system are you using?

mac os

What CPU architecture are you using?

x86_64

What Node versions, OSs and CPU architectures are you building for?

node20

Describe the Bug

I want to fork a child process in packaged executable, but something error occoued:

{
    "errno": -2,
    "code": "ENOENT",
    "syscall": "spawn /Applications/budding.app/Contents/MacOS/app",
    "path": "/Applications/budding.app/Contents/MacOS/app",
    "spawnargs": [
        "/snapshot/budding/dist/services/broker.js",
        1,
        "channel=fb"
    ]
}

services/broker.js has set to assets but no effect

Expected Behavior

fork process can work

To Reproduce

// package.json
{
  "name": "pkg-test",
  "version": "1.0.0",
  "main": "index.js",
  "bin": "dist/server.js",
  "license": "MIT",
  "dependencies": {},
  "devDependencies": {
    "@yao-pkg/pkg": "^5.12.0",
    "esbuild": "^0.21.5",
    "execa": "^9.2.0",
    "fs-extra": "^11.2.0",
    "ora": "^8.0.1"
  },
  "pkg": {
    "assets": [
      "./child.js"
    ]
  },
  "pkg.debug": {
    "assets": [
      "./child.js"
    ]
  }
}
// index.js
const path = require('path');
const {fork} = require('child_process');

fork(path.resolve(__dirname, '../child.js'), [], {
  cwd: __dirname
});
// child.js
setInterval(() => {
  console.log('child process');
}, 3000);
// script/build.js
import fs from 'node:fs';
import {execa} from 'execa';
import path from 'node:path';
import { oraPromise } from 'ora';

const isDebug = true;

const isWin = process.platform === 'win32';
const PKG_CONFIG_FILENAME = isDebug
  ? '.pkg.debug.config.json' : '.pkg.config.json';

async function createBundle() {
  return execa('node_modules/.bin/esbuild', [
    './index.js',
    '--bundle',
    ...(isDebug ? [] : ['--minify', '--keep-names']),
    '--outfile=dist/server.js',
    '--platform=node',
    '--loader:.node=file',
    ...((cwd) => {
      const {dependencies} = JSON.parse(
        fs.readFileSync(path.resolve(cwd, 'package.json'), 'utf8')
      );

      return Object.keys(dependencies).map((pkg) => {
        return `--external:${pkg}`;
      });
    })(process.cwd())
  ]);
}

async function createPkgConfig(debug, configFile) {
  const cwd = process.cwd();

  const {
    bin,
    name,
    version,
    description,
    dependencies,
    ...packageJson
  } = JSON.parse(
    fs.readFileSync(path.resolve(cwd, 'package.json'), 'utf8')
  );

  let pkgConfig;
  if (debug) {
    pkgConfig = packageJson['pkg.debug'];
  } else {
    pkgConfig = packageJson.pkg;
  }

  for (let pkg of Object.keys(dependencies)) {
    pkgConfig.assets.push(`node_modules/${pkg}`);
  }

  fs.writeFileSync(
    path.resolve(cwd, configFile), JSON.stringify({
      bin,
      name,
      version,
      description,
      dependencies,
      pkg: pkgConfig
    }, void(0), 2), 'utf8'
  );
}

async function createServerPackage(configFile) {
  return execa('node_modules/.bin/pkg', [
    configFile,
    ...(isDebug ? [] : ['--compress', 'Brotli']),
    '--output', isWin ? 'bin/app.exe' : 'bin/app'
  ]);
}

async function main() {
  try {
    await createPkgConfig(isDebug, PKG_CONFIG_FILENAME);

    await createBundle();

    await createServerPackage(PKG_CONFIG_FILENAME);
  } catch (e) {
    console.log(e);
    throw e;
  }
}

oraPromise(main, {
  text: 'Building server...\n',
  successText: 'Done\n',
  failText: 'Cannot build server'
});
// script/package.json
{
  "type": "module"
}
// build executable
node script/build.js

// run 
./bin/app

node:events:496
      throw er; // Unhandled 'error' event
      ^

Error: spawn /Users/kjh/Projects/test/pkg-test/bin/app ENOENT
    at ChildProcess._handle.onexit (node:internal/child_process:286:19)
    at onErrorNT (node:internal/child_process:484:16)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)
    at process.runNextTicks [as _tickCallback] (node:internal/process/task_queues:64:3)
    at Function.runMain (pkg/prelude/bootstrap.js:1984:13)
    at node:internal/main/run_main_module:28:49
Emitted 'error' event on ChildProcess instance at:
    at ChildProcess._handle.onexit (node:internal/child_process:292:12)
    at onErrorNT (node:internal/child_process:484:16)
    [... lines matching original stack trace ...]
    at node:internal/main/run_main_module:28:49 {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn /Users/kjh/Projects/test/pkg-test/bin/app',
  path: '/Users/kjh/Projects/test/pkg-test/bin/app',
  spawnargs: [ '/snapshot/pkg-test/dist/child.js' ]
}