PHP通过exec传变量到Node.js(minimist)时数值末尾异常变更
Hey there! Let's break down why your Discord user ID is getting mangled when passing it from PHP to Node.js, and how to fix this for good.
The Root Cause: JavaScript Number Precision Limits
Here's the core issue: JavaScript uses 64-bit floating-point numbers (the Number type) for all numeric values, and these have a hard limit on exactly representable integers. That limit is 2^53 (equal to 9007199254740992).
Your user ID, 346236693579300867, is way larger than this threshold (it’s around 3.4×10¹⁷). When Node.js/minimist tries to parse it as a number, it can’t store all the digits accurately, so it rounds the value to the closest representable floating-point number—hence why you’re seeing 346236693579300860 instead of the original ID.
Two Simple, Reliable Fixes
Since Discord user IDs are designed to be treated as strings (not numbers), we just need to ensure Node.js keeps the ID as a string instead of trying to convert it to a Number. Here are two easy ways to do this:
Fix 1: Quote the User ID in PHP’s Exec Call
Wrap the $userid variable in single quotes when passing it to the Node.js script. This tells the shell (and minimist) to treat it as a string, not a numeric value:
exec("node myscript.js --userid='$userid' &", $output);
Fix 2: Force Minimist to Parse User ID as a String
Modify your Node.js script to explicitly tell minimist that the userid parameter should be parsed as a string using the string option. This works even if you don’t quote the value in PHP:
var argv = require('minimist')(process.argv.slice(2), { string: ['userid'] }); discord.sendMessage("Welcome " + "<@" + argv.userid + ">");
Why This Works
Discord’s mention format (<@USER_ID>) expects the ID to be a string anyway, so keeping it as a string doesn’t break anything—it just preserves the exact value you passed from PHP. No more rounding errors!
内容的提问来源于stack exchange,提问作者Justin Jones

