系统信息
当我试图上传一个长名称的文件时,就会出现以下错误:
error: ENAMETOOLONG: name too long
文件名:Lorem Ipsum只是印刷和排版行业的虚拟文本。自从1500年代以来,Lorem Ipsum就一直是业界标准的虚拟文本,当时一台不知名的打印机拿出一台打字机,在这里翻炒一本样书a.pdf。
有人能帮我找出这个错误的根本原因吗?
发布于 2022-06-27 11:46:09
这是你的文件系统。您的示例文件名看起来确切地是255个字节,但是其中有一个“花式引号”。它不是撇号(0x27)或反号(0x60),而是三个字节( 0x2e 0x80 0x99
)。错误是完全正确的:名称太长了。
您可以检查这个列表。,搜索字符U+2019
,您将看到这个字节序列与您的引号字符匹配。
JavaScript的字符串函数(比如''.substr()
)可以处理字符而不是字节,因此简单地使用filename.substr(0, 255)
是行不通的。
最好的方法是使用一个外部包,它知道如何在不中断特殊字符序列的情况下修剪UTF-8字符串,比如多字节引号或表情符号。
const truncate = require('truncate-utf8-bytes');
const { extname, basename } = require('path');
function trimFilenameToBytes(filename, maxBytes = 255) {
// By extracting the file extension from the filename,
// it'll trim "verylong.pdf" to "verylo.pdf" and not "verylong.p"
const ext = extname(filename);
const base = basename(filename, ext);
const length = Buffer.byteLength(ext);
const shorter = truncate(base, Math.max(0, maxBytes - length)) + ext;
// Just in case the file extension's length is more than maxBytes.
return truncate(shorter, maxBytes);
}
const filename = 'Lorem Ipsum is simply dummy \
text of the printing and typesetting industry. Lorem Ipsum has \
been the industry’s standard dummy text ever since the 1500s, \
when an unknown printer took a galley of type and scrambled it \
to make a type specimen book here a.pdf';
console.log(
'This string is',
filename.length,
'characters and',
Buffer.byteLength(filename, 'utf-8'),
'bytes'
);
console.log(trimFilenameToBytes(filename));
// Will log the following, note how it's 2 bytes shorter:
// This string is 255 characters and 257 bytes
// Lorem Ipsum is simply dummy \
// text of the printing and typesetting industry. Lorem Ipsum has \
// been the industry’s standard dummy text ever since the 1500s, \
// when an unknown printer took a galley of type and scrambled it \
// to make a type specimen book here.pdf
https://stackoverflow.com/questions/72770974
复制相似问题