node.js - 将文件名推送到数组,然后将它们写入文本文件
问题描述
好的,所以我制作了一个小的 nodejs FTP 上传器,它可以上传我存储在本地目录中的文件并将它们传输到我的网络服务器。
上传文件后,我试图让它在一个recent.txt
文件中附加信息,该文件包括 web url 和上传到该 url 的文件。
但是我在尝试.push();
将文件名放入dirFiles
数组时遇到了麻烦。
const fs = require('fs');
const ftp = require("basic-ftp")
const open = require('open')
const path = require('path');
var ncp = require("copy-paste");
//random string for url gen function
function rand(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
//the actual upload
async function Upload() {
const client = new ftp.Client()
client.ftp.verbose = true
try {
await client.access({
host:
user:
password:
port:
})
client.trackProgress(info => {
console.log("File", info.name)
console.log("Type", info.type)
console.log("Transferred", info.bytes)
console.log("Transferred Overall", info.bytesOverall)
})
client.trackProgress(info => console.log(info.bytesOverall))
//needed variables for shit
var rand_string = rand(5); //can change this from rand to a previous upload folder
var share_url = `https://molex.cloud/${rand_string}`;
let uploadDir = `/HOSTED_WEBSITES/molexCloud/.sh/${rand_string}/`;
const localDir = '_upload_these/';
const recent = "recent.txt"
await client.ensureDir(uploadDir)
await client.uploadFromDir(localDir, uploadDir)
client.trackProgress()
//copy share url to clipboard
ncp.copy(share_url, function() {
open(share_url);
})
// formatting for the recent.txt
let date_ob = new Date();
let date = ("0" + date_ob.getDate()).slice(-2);
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
let year = date_ob.getFullYear();
let hours = date_ob.getHours();
let minutes = date_ob.getMinutes();
//Array to store filenames
var dirFiles = [];
//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}`);
});
});
//seperators, date, and time
var _u = `__________________________________________________________`;
var _d = `..........................................................`;
var _t = `On ${month}-${date}-${year} at ${hours}:${minutes}`;
//format to store url in recent.txt
var linkFormat = `${_u}\n\n ${share_url}\n${_d}\n ${dirFiles}\n${_d}\n ${_t}\n${_u}\n>\n`;
// EXAMPLE:
// __________________________________________________________
//
// https://molex.cloud/aB123
// ..........................................................
// test.txt
// test.png
// ..........................................................
// On MM-DD-YYYY at HH:MM
// __________________________________________________________
// >
//
try {
//check if recent.txt exists
if (fs.existsSync(recent)) {
//append recent.txt
fs.appendFileSync(recent, linkFormat);
console.log('\x1b[33m%s\x1b[0m', `Adding url to list .............. ${share_url}`);
} else {
//create and append
fs.writeFileSync(recent, linkFormat, err => {
if (err) {
console.error(err);
return;
}
//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}`);
})
}
} catch (err) {
console.error(err);
}
} catch (err) {
console.log(err);
}
//console info
console.log('\n');
console.log(`\x1b[36m%s\x1b[0m`, `Opening default web browser...`);
console.log('\n');
console.log('\x1b[36m%s\x1b[0m', 'Link copied to clipboard...');
console.log('\n');
console.log('\x1b[32m%s\x1b[0m', `Shareable Link:`);
console.log(`\x1b[30m\x1b[42m\x1b[4m%s\x1b[0m`, `${share_url}`);
console.log('\n');
console.log('\x1b[32m%s\x1b[0m', `Type \x1b[35m'links'\x1b[32m in the terminal for a list of recent uploads.\x1b[0m`);
client.close();
}
Upload();
解决方案
抱歉,我仍在学习整个异步、等待、同步和范围。我仍在尝试在同步 FS 方法上使用回调函数。
//scan local dir to add filenames to dirFiles array
var files = fs.readdirSync(localDir);
//push to array in foreach
files.forEach(function(file) {
dirFiles.push(file);
console.log(`PUSHING: ${file}`);
});
// create a string with all of the dirFiles elements, split by newline
var fileString = dirFiles.join('\n');
推荐阅读
- django - Django websockets 身份验证
- android - 为什么我对一个包中的代码所做的更改没有反映在实际的应用程序中?
- java - 什么java数据结构适合像kafka这样的基于偏移量的单分区日志?
- c++ - 将类中声明的函数作为参数传递会导致编译错误
- apache-spark - 将带有纳秒的字符串转换为时间戳
- html - 带有 xsl 的 xpath:测试时
- c# - 使 8 x 8 网格具有正确的 FEN 表示法。像棋盘
- c++ - 在循环初始化中使用带有静态的 constexpr?
- android - Android Paging Library - 具有多种排序类型的数据+网络
- python - Python-Camelot 提取空表