Javascript 完成后无法退出我的进程。NodeJS
我正在开发一个NodeJS程序,用于连接到远程SFTP服务器以复制日志文件。我正在使用这个NPM包 代码按预期工作,但问题是我无法终止会话。程序只是在完成复制文件操作后等待。Javascript 完成后无法退出我的进程。NodeJS,javascript,node.js,sftp,Javascript,Node.js,Sftp,我正在开发一个NodeJS程序,用于连接到远程SFTP服务器以复制日志文件。我正在使用这个NPM包 代码按预期工作,但问题是我无法终止会话。程序只是在完成复制文件操作后等待。sftp.end()调用在复制完成之前过早地关闭了连接。如果我删除该程序,只需在复制完成后等待 我不确定在哪里写sftp.end()行来终止程序 编辑1:使用Promise.all和async/await now更新代码 将我的代码分成几部分,现在使用async/await以提高可读性。节目现在结束了。不再等待或挂起,但问题
sftp.end()
调用在复制完成之前过早地关闭了连接。如果我删除该程序,只需在复制完成后等待
我不确定在哪里写sftp.end()
行来终止程序
编辑1:使用Promise.all和async/await now更新代码
将我的代码分成几部分,现在使用async/await以提高可读性。节目现在结束了。不再等待或挂起,但问题是文件没有被复制。我看到一条控制台消息“从源目录复制的文件”
简言之,当你有一系列承诺(a.then(()=>b.then(()=>…
)并且你想在承诺的末尾做点什么时,你只需将这些东西添加到最后一个。然后
回调中
但是,如果您要做出多个承诺,则需要等到所有承诺都完成,您可以使用Promise.all
():
为此,您需要将所有的
forEach
调用转换为map
调用,这些调用返回它们创建的承诺。一旦这样做,map
操作将返回这些承诺的数组,您可以将其与Promise一起使用。所有您正在使用的forEach
循环执行同步tes,不保存函数返回值,并在forEach
返回时立即调用sftp.end()
。继续之前,请查找有关在异步代码中使用forEach
的问题。:-)谢谢。我们将对此进行研究。将我的代码拆分为函数并使用async/Wait now。请参阅编辑1,不幸的是,这仍然不起作用。如果要这样做,您需要切换到语言级别(让i=0;i
style。您必须记住,即使在函数上使用async
,它真正的意思是“此函数返回一个承诺”..forEach
不知道如何处理承诺,因此您要么不使用它,要么使用映射
,然后将承诺数组传递回承诺。所有这些
。这帮助我解决了问题。谢谢!
const main = () => {
const servers = ['server list'];
servers.forEach((s) => {
const sftp = new Client();
// Connect to the server
sftp.connect({
host: s,
port: '22',
username: '',
password: '',
}).then(() => logger.log(`Connected to ${s}`))
// get list of directories
.then(() => sftp.list(rootLogPath))
.then((dirs) => {
dirs.forEach((d) => {
const target = createTargetDirectory(d.name);
// list all files in the directory
sftp.list(`${rootLogPath}/${d.name}`)
.then((files) => {
// filter only today's files
const todayFiles = files.filter((f) => f.type === '-' && moment().format('MMDDYYYY') === moment(f.modifyTime).format('MMDDYYYY'));
// copy today's files into target
todayFiles.forEach((f) => {
sftp.get(`${rootLogPath}/${d.name}/${f.name}`, `${target}/${f.name}`)
.then(() => logger.log(`Copied ${f.name} from ${d.name} located on ${s}`));
});
});
});
return sftp.end();
})
.catch(() => logger.log(`Connection to ${s} failed`));
});
};
main();
const copyTodayFiles = async (src) => {
try {
let fileList = await sftp.list(`${rootLogPath}/${src}`);
fileList = fileList.filter(
(f) => f.type === '-' && moment().format('MMDDYYYY') === moment(f.modifyTime).format('MMDDYYYY'),
);
const target = createTargetDirectory(src);
if (target) {
fileList.forEach(async (f) => {
try {
await sftp.get(`${rootLogPath}/${src}/${f.name}`, `${target}/${f.name}`);
logger.log(`Copied ${f.name}`);
} catch (error) {
logger.log(`Failed to copy ${f.name}`);
}
});
console.log(`Copied files from ${src}`);
}
} catch (error) {
logger.log(`Failed to read files from ${src}`);
logger.log(error);
}
};
const workOn = async (server) => {
sftp = new Client();
const config = {
host: server,
port: '22',
username: '',
password: '',
};
try {
await sftp.connect(config);
logger.log(`Connection to ${server} is successful.`);
const logDir = await sftp.list(rootLogPath);
Promise.all(logDir.map((d) => copyTodayFiles(d.name))).then(() => sftp.end());
// logDir.forEach(async (d) => copyTodayFiles(d.name));
} catch (error) {
logger.log(`Connection to ${server} failed.`);
logger.log(error);
}
};
const main = () => {
const servers = ['server list'];
Promise.all(servers.map((s) => workOn(s)));
};
main();
Promise.all([promise1, promise2]).then(...