node.js打包可执行文件

3,493 阅读1分钟

这个项目很神奇,直接将node.js项目打包成windows可以直接执行的exe文件(也支持FreeBSD、linux、macos、arm系统),甚至不需要安装Node.js,且无须修改你项目中的任何代码!

ps:由于路径原因,此代码只能在打包后执行!

1、创建一个文件目录

mkdir nodepkg

2、初始化nodepkg

cd nodepkg
npm init

3、新建一个index.js作为项目入口文件

touch index.js
npm install -g pkg

4、配置package.json

"bin": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"pkg": "pkg . -t index.js"
},
"pkg": {
    "scripts": [],
    "targets": [
      "node10-macos-x64",   // mac执行
      "node10-win-x64"      // win执行
    ]
}

5、打包文件,初次打包有点慢

pkg .

6、编写index.js,实现日志功能

npm i log4js
touch application.log
const log4js = require('log4js');
log4js.configure({
    appenders: {
        out: { type: 'stdout' },
        app: { type: 'file', filename: path.join(path.dirname(process.execPath) , './application.log') }
        },
        categories: {
        default: { appenders: [ 'out', 'app' ], level: 'debug' }
    }
});
 
let logger = log4js.getLogger();

logger.debug('===日志打印===');

7、实现文件删除

mkdir fail
const failPath = path.join(path.dirname(process.execPath), '/fail')

// 删除临时文件  fs.rmdir不能删除有文件的文件夹
if( fs.existsSync(failPath) ) {// 判断文件夹是否有文件
    // 定义名字数组
    let files = [];
    // 文件名字添加到数组
    files = fs.readdirSync(failPath);
    // 遍历文件名
    files.forEach((file,index) => {
        let curPath = failPath + "/" + file;
        // 删除文件
        fs.unlinkSync(curPath)
    });
}

8、实现数据请求

npm i request
touch config.txt
let baseUrl = fs.readFileSync(path.join(path.dirname(process.execPath) , '/config.txt'));   // 此文件作为配置文件,可以随意请求你想要的接口数据

// 获取名字接口
function getNameList(){
    return new Promise((resolve, reject) =>{
        request(`${baseUrl}/nameList?name=`, function (error, response, body) {
            body = JSON.parse(body)
            if(body.status === 200){
                resolve(body.data)
            }
        })
    }).catch((err) => {
        console.log(err)
    })
};

9、读取一个文件夹所有文件

const filePath = path.join(path.dirname(process.execPath), '/dist') // 我这个文件夹放的照片

let files = fs.readdirSync(filePath);

if(files[0] === '.DS_Store') files.splice(0,1);

10、一个文件夹照片写入另一个文件夹

for(let i = 0 , len = files.length ; i < len ; i++){
    let writerStream = await fs.createWriteStream(failPath + `/${files[i]}`);
    let readStream = await fs.readFileSync(filePath + `/${files[i]}`)
    console.log(readStream)
    writerStream.write(readStream,"UTF-8");
    writerStream.end();
    writerStream.on('finish', function() {
        console.log("写入完成");
    });
    writerStream.on('error', function(err) {
        console.log(err.stack);
    });
    console.log("execute end...");
}