这是具有2个功能的文件“path-info.js”:pathInfo &回调。 Pathinfo收集关于来自对象“info”中路径的文件的所有信息,回调获取该对象并将其返回。代码:我的回拨有什么问题?
"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;
我用我的回调函数,因为它显示出,例如,在这里:nodeJs callbacks simple example。尽管如此,这段代码不起作用,我不知道为什么。
我打电话使用文件“test.js”这段代码,这里是代码:
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);
所以逻辑是,我需要给我的回调,其中包含有关目录或文件的一些信息的对象。根据不同的情况,会显示一些console.log。
任何帮助将不胜感激!
UPD:更新了代码,只是将我的“回调”函数重命名为“getInfo”。
定义“不工作' –
这是因为你在你的'path-info.js'中声明了一个名为'callback'的变量,重命名它并且它将解决你的问题 –
你得到了什么错误信息? –