這是具有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'的變量,重命名它並且它將解決你的問題 –
你得到了什麼錯誤信息? –