在 Windows PowerShell 中写入含特殊字符的 Node.js/JS 文件时,PowerShell 会破坏文件内容。此 Skill 提供诊断和修复方法。
问题表现原因反引号被吞模板字符串 `hello ${name}` → "hello ${name}"PowerShell 把 ` 当转义符$ 变量被展开${var} 变空字符串PowerShell 展开 $var 变量中文变乱码汉字变垃圾字符(如 已查到)UTF-8 被 GBK 重编码文件体积暴增13KB → 20MB乱码字符被反复替换
PowerShell 管道命令会修改文件编码:
powershell
# ❌ 这些命令会破坏文件:
Set-Content file.js "content" # 吞反引号
Out-File file.js # 吞反引号
Get-Content | Set-Content # 管道 → 重编码
Write-Output "`$var" > file.js # 展开 $ 变量
本 Skill 附带一个可执行脚本 pwsh-encoding-fix.js,可以在任何有 Node.js 的 Windows 机器上运行:
bash
# 诊断文件编码问题
node pwsh-encoding-fix.js <文件路径>
# 诊断并自动修复(仅 GBK 乱码可自动修复)
node pwsh-encoding-fix.js <文件路径> --fix
严重度检测类型说明!! CRITICALBACKTICK_LOST模板字符串反引号被 PowerShell 吞掉!! CRITICALDOLLAR_EXPANDED${var} 变量被展开为空!! CRITICALGBK_CORRUPT中文 UTF-8 被 GBK 重编码损坏(可自动修复)!! CRITICALSYNTAX_ERRORJS 语法检查失败,可能是编码损坏导致WW WARNINGBACKTICK_PARTIAL部分模板可能受损WW WARNINGGBK_CORRUPT (mild)部分中文可能受损II LOWBOM文件含 UTF-8 BOM 头(不影响运行但不够干净)
text
========================================================
PowerShell Encoding Damage Report
========================================================
File: C:\project\server.js
Size: 17.9 KB (408 lines)
Backtick: 0
Dollar{}: 15 total
Suspicious lines: 12 / 12
Chinese: 1257 valid / 242 GBK residual
Syntax: FAIL
--------------------------------------------------------
Found 3 issue(s):
!! [CRITICAL] BACKTICK_LOST
12 lines use ${} without backticks. Template literals stripped.
!! [CRITICAL] GBK_CORRUPT
GBK residual: 242 chars / valid Chinese: 1257 (ratio 0.2)
!! [CRITICAL] SYNTAX_ERROR
Unexpected token ...
--------------------------------------------------------
Critical issues found. Use --fix to attempt repair.
powershell
node -e "fs.writeFileSync('file.js', 'content', 'utf8')"
注意: -e 字符串中的 $ 仍会被 PowerShell 展开,需要用单引号包裹或转义。
直接使用 write 工具创建文件,不走 PowerShell 管道。
在干净机器上生成 hex:
bash
node -e "const fs=require('fs');const h=fs.readFileSync('file.js').toString('hex');console.log(h)" > file.hex
在目标机器上恢复:
bash
node -e "const fs=require('fs');fs.writeFileSync('file.js',Buffer.from(fs.readFileSync('file.hex','utf8').trim(),'hex'))"
powershell
# 检查语法
node --check file.js
# 检查 BOM 头(正确的文件头应是 63 6f 6e = "con")
node -e "const fs=require('fs');const b=fs.readFileSync('file.js');console.log(b[0].toString(16),b[1].toString(16),b[2].toString(16))"
# 检查反引号数量
node -e "const fs=require('fs');const c=fs.readFileSync('file.js','utf8');const bt=String.fromCharCode(96);console.log('Backtick count:',c.split(bt).length-1)"
Get-Content | Set-Contentfs.readFileSync('file.js', 'utf8')--fix 模式自动修复,或用 find/replace 映射write 工具直接从原始源码完整重写write 工具代替 PowerShell 写文件node --check 验证语法writeFileSync 或 hex 编码写入路径说明SKILL.md本文档pwsh-encoding-fix.js可执行诊断修复工具(Node.js脚本)
只需将 pwsh-encoding-fix.js 拷贝到目标机器(任何 Windows 系统),确保已安装 Node.js:
bash
# 从本目录复制到目标机器
# 然后在目标机器上运行
node pwsh-encoding-fix.js 需要检查的文件.js
node pwsh-encoding-fix.js 需要检查的文件.js --fix
无需安装任何 npm 包。GBK 修复需要 iconv-lite(自动检测,无则回退到内置 TextDecoder)。