gpt4 book ai didi

javascript - Node.Js 尝试通过另一个文件中的函数打印 JSON 数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:37 26 4
gpt4 key购买 nike

尝试将所有管理器的 JSON 数组打印到我的本地主机,但我看到的是空白屏幕。数组填充正确,问题(最有可能)出现在 server.js 文件中。我不确定是什么。任何帮助表示赞赏。编辑:对于原始帖子中缺少一些代码表示歉意

//server.js

var HTTP_PORT = process.env.PORT || 8080;
var express = require('express');
var data = require('./data-service');
var getManagers = require('./data-service');
var fs = require('fs');
var app = express();




app.get('/managers', function(req,res){
var responseObject = getManagers();
res.send(responseObject);
});

app.listen(8080, function(){
});
app.use(express.static('public'));

//data-server.js

var employees = [];
var departments = [];
var error = 0;
var fs = require("fs");

function initialize(){

employees = fs.readFileSync("./data/employees.json", 'utf8', function(err, data){
if(err){
error = 1;
}
employees = JSON.parse(data);

});


departments = fs.readFileSync("./data/department.json", 'utf8',function(err, data){
if(err){
error = 1;
}
departments = JSON.parse(data);

});
}

function check() {
return new Promise(function(resolve,reject){

if (error === 0){
resolve("Success");

}
else if(error === 1){
reject("unable to read file");
}
})
};

var getManagers = function(){
check().then(function(){
var employees2 = JSON.parse(employees);
for (var i = 0; i < employees2.length; i++){
if(employees2[i].isManager == true){
console.log(employees2[i]);
}
}
}).catch(function(){
console.log("no results found");
})
}

initialize();
module.exports = getManagers;

最佳答案

确保在类的构造函数中调用initialize

// Let's assume we create a Node module called
// 'myobject' from this.

function MyObject() {

this.initialize();
}

MyObject.prototype = {
initialize: function() {
.... //use this.employees
}

check: function() {
...
},
getManager: function(){
...//use this.employees
}
};

module.exports = MyObject;

调用此模块应如下所示:

var MyObject = require('myobject');

var m = new MyObject();
m.getManagers();

关于javascript - Node.Js 尝试通过另一个文件中的函数打印 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46555740/

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