gpt4 book ai didi

javascript - nodejs - 等待 fs.stat 完成

转载 作者:行者123 更新时间:2023-11-30 15:15:44 24 4
gpt4 key购买 nike

我有一个从 C# 迁移到 nodejs 的同步过程,它每天检查目录中的某些文件。如果这些文件存在,它会将它们添加到 TAR 文件并将该 TAR 写入不同的目录。在使用 forEach 循环检查任何相关文件时,我努力让我的进程等待循环完成,然后再转到下一个函数,以创建 TAR 文件。

我已经按照建议尝试使用 async 模块 here并按照建议 promise here .没有太大的成功。

通过使用 async 模块,我希望停止执行命令,以便我的循环可以在返回 fileList 数组之前完成。目前,我收到了 TypeError: Cannot read property 'undefined' of undefined

我的问题:async 是否会停止执行直到我的循环完成,如果是这样我做错了什么?

感谢您的关注,请查看下面我的代码。

var fs = require('fs'), // access the file system.
tar = require('tar'), // archiving tools.
async = require('async'), // async tool to wait for the process's loop to finish.
moment = require('moment'), // date / time tools.
source = process.env.envA, // environment variable defining the source directory.
destination = process.env.envB, // environment variable defining the destination directory.
archiveName = process.env.envArc, // environment variable defining the static part of the TAR file's name.
searchParameter = process.env.env1, // environment variable defining a file search parameter.
date = moment().format('YYYYMMDD'); // Create a date object for file date comparison and the archive file name.

// Change working directory the process is running in.
process.chdir(source);

// Read the files within that directory.
fs.readdir(source, function (err, files) {
// If there is an error display that error.
if (err) {
console.log('>>> File System Error: ' + err);
}

// **** LOOP ENTRY POINT ****
// Loop through each file that is found,
// check it matches the search parameter and current date e.g. today's date.
CheckFiles(files, function (fileList) {
// If files are present create a new TAR file...
if (fileList > 0) {
console.log('>>> File detected. Starting archiveFiles process.');
archiveFiles(fileList);
} else { // ...else exit the application.
console.log('>>> No file detected, terminating process.');
//process.exit(0);
}
});
});

var CheckFiles = function (files, callback) {
console.log('>>> CheckFiles process starting.');

var fileList = []; // Create an empty array to hold relevant file names.

// **** THE LOOP IN QUESTION ****
// Loop through each file in the source directory...
async.series(files.forEach(function (item) {
// ...if the current file's name matches the search parameter...
if (item.match(searchParameter)) {
// ...and it's modified property is equal to today...
fs.stat(item, function (err, stats) {
if (err) {
console.log('>>> File Attributes Error: ' + err);
}
var fileDate = moment(stats.mtime).format('YYYYMMDD');

if (fileDate === date) {
// ...add to an array of file names.
fileList.push(item);
console.log('>>> Date match successful: ' + item);
} else {
console.log('>>> Date match not successful:' + item);
}
});
}
}), callback(fileList)); // Once all the files have been examined, return the list of relevant files.
// **** END LOOP ****

console.log('>>> CheckFiles process finished.');
};

var archiveFiles = function (fileList) {
console.log('>>> Starting archiveFiles process.');

if (fileList.length > 0) {
// Tar the files in the array to another directory.
tar.c({}, [fileList[0], fileList[1]]).pipe(fs.createWriteStream(destination + archiveName));
// TODO Slack notification.
console.log('>>> TAR file written.');
}
};

最佳答案

Async 是不必要的,按照@I'm Blue Da Ba Dee 的建议使用Promises 和按照由建议的fs.statSync @Cheloid 满足了我的要求。对于可能从此结果中受益的任何人,请参阅下面的代码。

var fs = require('fs'), // access the file system.
tar = require('tar'), // archiving tools.
moment = require('moment'), // date / time tools.
source = process.env.envA, // environment variable defining the source directory.
destination = process.env.envB, // environment variable defining the destination directory.
archiveName = process.env.envArc, // environment variable defining the static part of the TAR file's name.
searchParameter = process.env.env1, // environment variable defining a file search parameter.
date = moment().format('YYYYMMDD'), // create a date object for file date comparison and the archive file name.
fileList = [], // create an empty array to hold relevant file names.
slack = require('./slack.js'); // import Slack notification functionality.

// Change working directory the process is running in.
process.chdir(source);

// Read the files within that directory.
fs.readdir(source, function (err, files) {
// If there is an error display that error.
if (err) console.log('>>> File System Error: ' + err);

// Loop through each file that is found...
checkFilesPromise(files).then(function (response) {
console.log('>>> File(s) detected. Starting archiveFilesPromise.');

// Archive any relevant files.
archiveFilesPromise(fileList).then(function (response) {
console.log('>>> TAR file written.');

// Send a Slack notification when complete.
slack('TAR file written.', 'good', response);
}, function (error) {
console.log('>>> archiveFilesPromise error: ' + error);
slack('archiveFilesPromise error:' + error, 'Warning', error);
});
}, function (error) {
console.log('>>> CheckFilesPromise error ' + error);
slack('CheckFilesPromise error: ' + error, 'Warning', error);
});
});

var checkFilesPromise = function (files) {
return new Promise(function (resolve, reject) {
files.forEach(function (item) {
// ...check it matches the search parameter...
if (item.match(searchParameter)) {
var stats = fs.statSync(item);
var fileDate = moment(stats.mtime).format('YYYYMMDD');

// ...and current date e.g. today's date.
if (fileDate === date) {
// Add file to an array of file names.
console.log('>>> Date match successful, pushing: ' + item);
fileList.push(item);
resolve('Success');
} else {
reject('Failure');
}
}
});
});
};

var archiveFilesPromise = function (list) {
return new Promise(function (resolve, reject) {

if (list.length > 0) {
// Tar the files in the array to another directory.
tar.c({}, [list[0], list[1]]).pipe(fs.createWriteStream(destination + date + archiveName));
resolve('Success');
} else {
reject('Failure');
}
});
};

关于javascript - nodejs - 等待 fs.stat 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44501109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com