This is the file "path-info.js" that has 2 functions: pathInfo & callback. Pathinfo collects all info about file from path in the object "info", callback gets that object and returns it. Code:
"use strict";
const fs = require("fs");
let getInfo = function (err, someObject) {
if (err) throw err;
return someObject;
};
function pathInfo(path, callback) {
let info = {};
info.path = path; // write path info
fs.stat(path, (err, type) => { // write type info
if (type.isFile()) {
info.type = "file";
}
if (type.isDirectory()) {
info.type = "directory";
} else {
info.type = "undefined";
}
});
fs.stat(path, (err, type) => { // write content info if it is file
if (type.isFile()) {
fs.readFile(path, "utf8", (err, content) => {
info.content = content;
});
} else {
info.content = "undefined";
}
});
fs.stat(path, (err, type) => { // write childs if it is directory
if (type.isDirectory()) {
fs.readdir(path, (err, childs) => {
info.childs = childs
});
} else {
info.childs = "undefined";
}
});
getInfo(null, info); // callback returns object "info"
}
module.exports = pathInfo;
I use my callback function as it was shown, for instance, here: nodeJs callbacks simple example. Still, this code does not work and I do not why.
I call this code using file "test.js", here is the code:
const pathInfo = require('./path-info');
function showInfo(err, info) {
if (err) {
console.log('Error occurred');
return;
}
switch (info.type) {
case 'file':
console.log(`${info.path} — is File, contents:`);
console.log(info.content);
console.log('-'.repeat(10));
break;
case 'directory':
console.log(`${info.path} — is Directory, child files:`);
info.childs.forEach(name => console.log(` ${name}`));
console.log('-'.repeat(10));
break;
default:
console.log('Is not supported');
break;
}
}
pathInfo(__dirname, showInfo);
pathInfo(__filename, showInfo);
So the logic is that I need to give my callback the object that contains some info about directory or file. Depending on that, some console.logs will be displayed.
Any help will be appreciated!
UPD: updated the code, just renamed my "callback" function to "getInfo".