You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js FTP上传工具无法将文件名push入数组写入recent.txt问题

问题原因

你混淆了Node.js文件系统API中同步和异步方法的用法:fs.readdirSync()是同步读取目录的API,直接返回文件名称数组,不会执行你传入的回调函数,因此你写在回调里的push操作从来没有执行过,dirFiles数组始终是空值,最终写入recent.txt时自然没有文件名展示。

同时你的代码里还有一处小问题:fs.writeFileSync()也是同步API,你传入的回调函数同样不会执行,属于无效逻辑。

修复方案

替换你代码中读取目录和格式化文件名的对应片段即可:

1. 替换读取目录的错误代码

把原来的这段:

//scan local dir to add filenames to dirFiles array
fs.readdirSync(localDir, function(err, files) {
    if (err) {
        console.error(err);
        return;
    }
    //push to array in foreach
    files.forEach(function(file) {
        dirFiles.push(file);
        console.log(`PUSHING: ${file}`);
    });
});

替换为:

//scan local dir to add filenames to dirFiles array
try {
    const files = fs.readdirSync(localDir);
    files.forEach(function(file) {
        dirFiles.push(file);
        console.log(`PUSHING: ${file}`);
    });
} catch (err) {
    console.error(err);
}

2. 调整文件名格式化逻辑(可选,适配你期望的每行一个文件名的展示效果)

原来直接把数组转字符串会得到逗号分隔的结果,把linkFormat里的${dirFiles}改成${dirFiles.join('\n ')}即可:

var linkFormat = `${_u}\n\n  ${share_url}\n${_d}\n  ${dirFiles.join('\n  ')}\n${_d}\n  ${_t}\n${_u}\n>\n`;

3. 移除fs.writeFileSync无效回调(可选)

把原来的fs.writeFileSync(recent, linkFormat, err => { ... })改为直接传参数即可:

fs.writeFileSync(recent, linkFormat);
//recent.txt created and file written successfully
console.log('\x1b[33m%s\x1b[0m', `Creating recent upload list ..... ${recent}`);
console.log('\x1b[33m%s\x1b[0m', `Adding url to list .............. ${recent}`);

内容的提问来源于stack exchange,提问作者Tony Wierdman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:15:11