@OdAs
Начинающий пайтон програмист

Node.js fs.readdir Undefined?

Добрый день. Разрабатываю веб приложение для друга на основе node.js и electron. Суть приложения в конвертировке файлов которые он берет с папки. Пользователь указывает полный путь к папке на пк в поле ввода, затем скрипт берет список файлов в этой папке и по одному конвертирует их записуя в созданую скриптом папку. Проблема в том что пролистав кучу форумов и как русскоязычный так и англоязычный StackOverflow я не смог решить проблему с fs.readdir().
Функция выводит Undefined и я просто не знаю чем исправлять. Решил обратиться к умным людям здесь на ХабрQ&A
Вот код:
var now = new Date();
var path = require("path");
var counter = 0;
var ffmpeg = require("ffmpeg");
const fs = require("fs");
const path2 = "Ready_Vidios";


class Video_Audio_Convertation  {
	constructor(f) {
		this.f = f;
	}
		 	convertation(){
			let newfilename = "${now.getMilliseconds()}.mp4";
			try{
				var process = new ffmpeg('${getnameoffolder()}\${f}');
				console.log('${getnameoffolder()}\${f}');
				process.then(function (video) {

						video
						.setAudioCodec('libfaac')
						.setAudioChannels(2)
						.save('${path2}\${newfilename}', function (error, file) {
								if (!error)
									console.log('Video file: ' + file);
		});

	}, function (err) {
		console.log('Error: ' + err);
	});
			}catch(e){
				console.log(e.code);
				console.log(e.msg);
			}
		}
}

function convertfunc(f){
	let video = new Video_Audio_Convertation();
	video.convertation(f);
}

function create_new_folder() {
	fs.mkdirSync(path2);
}

function getdirectories(path, callback) {
    fs.readdir(path, function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })
		console.log(content);
}

function ConvertMainFunc(folder_path) {
	try{
			console.log("f-path in func:"+folderpath.value);
			let txtlisttosend;

			if(fs.existsSync(path2)){
				getdirectories(folder_path.value, function(err, content){return content});
				console.log(content);
				txtlisttosend = "\n".join(content);
				for(let f in content){
					counter += 1;
					convertfunc(path.join(folder_path.value, f));
				}
			}

			if(fs.existsSync(path2) != true){
				create_new_folder();
				getdirectories(folder_path.value, function(err, content){return content});
				console.log(content);
				txtlisttosend = "\n".join(content);
				for(let f in content){
					counter += 1;
					convertfunc(path.join(folder_path.value, f));
			}
		}

		return txtlisttosend;

	}catch(err){
	}
}

function GetCounter() {
	return counter;
}

function ConvertOnPress(){

	let folder_path = document.getElementById("folderpath").value;
	console.log(folderpath.value);
	let res = ConvertMainFunc(folderpath);
	document.getElementById("outputlist").innerHTML=res;
	console.log(res);

	let ct = GetCounter();
	document.getElementById("nfiles").innerHTML="Number of converted files"+" "+ ct;
	console.log(ct);
}

function animateGrid() {

	anime({
  targets: '.stagger-visualizer .anim-row',
  scale: [
  {value: .1, easing: 'easeOutSine', duration: 500},
  {value: 1, easing: 'easeInOutQuad', duration: 1200}
  ],
  delay: anime.stagger(200, {grid: [13, 1], from: 'center'})
  });
}

document.querySelector(".button").onclick = function(){
	ConvertOnPress();
	animateGrid();
}

Функция getdirectories() должна выдать список файлов content в деректории с которого в дальнейшем в цикле будут браться названия файлов для конвертировки. Собственно эта функция и возвращает Undefined...
Буду очень рад получить конструктивный ответ от специалиста!
  • Вопрос задан
  • 405 просмотров
Решения вопроса 1
john36allTa
@john36allTa
alien glow of a dirty mind
и не должна
у вас content возвращается в пустоту..

function ConvertMainFunc(folder_path) {
  try{
      console.log("f-path in func:"+folderpath.value);
      let txtlisttosend;

      if(fs.existsSync(path2)){
        getdirectories(folder_path.value, function(err, content){return content});
// return куда?
console.log(content);
// где определена переменная content?


Первый вариант решения: использовать fs.readdirSync
Второй вариант: переписать нормально логику или использовать промисы с async/await

Чтобы стало понятнее, измените код функции и гляньте консоль
function getdirectories(path, callback) {
    fs.readdir(path, function (err, content) {
        if (err) return callback(err)
        console.log(content);
        callback(null, content)
    })
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы