最近测试使用pkg对nodejs开发的项目进行打包,项目文件结构如下:
src/app.ts代码如下
import fs from "fs";
import path from "path";
// console.log(__dirname);
console.dir(fs.readdirSync(path.join(__dirname, "..")));
fs.cpSync(path.join(__dirname, "..", "assets"), path.join("c:", "test-setup"), {
recursive: true,
});
package.json中的pkg配置如下
"pkg": {
"scripts": "dist/**/*.js",
"assets": [
"assets/**/*.*"
],
"targets": [
"node16-win-x64"
],
"compress": "GZip",
"outputPath": "bin"
}
typescirpt的编译输出目录为dist。
按现在代码,可以直接成功运行,但打包后,程序报错,输出如下:
[ 'package.json', 'dist', 'assets' ]
node:internal/fs/utils:345
throw err;
^
Error: ENOENT: no such file or directory, lstat '\\?\C:\snapshot\setup\assets'
at Object.lstatSync (node:fs:1529:3)
at lstatSync (pkg/prelude/bootstrap.js:1506:33)
at statFunc (node:internal/fs/cp/cp-sync:114:15)
at getStatsSync (node:internal/fs/cp/cp-sync:115:19)
at checkPathsSync (node:internal/fs/cp/cp-sync:64:33)
at cpSyncFn (node:internal/fs/cp/cp-sync:58:33)
at Object.cpSync (node:fs:2855:3)
at Object.<anonymous> (C:\snapshot\setup\dist\app.js:10:14)
at Module._compile (pkg/prelude/bootstrap.js:1930:22)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) {
errno: -4058,
syscall: 'lstat',
code: 'ENOENT',
path: '\\\\?\\C:\\snapshot\\setup\\assets'
}
通过错误输出可以看到,在pkg生成的snapshot目录结构中,是存在目录:C:\snapshot\setup\assets,但输出报错误,目录不存在。
修改源代码为:
import fs from "fs";
import path from "path";
// console.log(__dirname);
console.dir(fs.readdirSync(path.join(__dirname, "..")));
fs.cpSync(path.join("..", "assets"), path.join("c:", "test-setup"), {
recursive: true,
});
修改后,不打包运行报错,提示目录不存在,但pkg打包后,执行生成的程序,可以成功执行。具体原因没有搞明白,有清楚的请告知,谢谢!
pkg版本为5.8.0