我有節點項目。 根文件是index.js
和文件helper.js
,在這裏我有一些幫助功能,它導入到index.js
。 我想獲取一些數據,使用helper.js
中的函數,但是當我在index.js
中調用它時,它將返回undefined
。 但在helper.js
以上是可以的,console.log
顯示我需要的數據。 我該如何解決這個問題?返回值時未定義
index.js文件內容:
const helper = require('./helper');
let data = helper.getData();
console.log(data); // undefined
helper.js文件內容:
const fs = require('fs');
module.exports = {
getData:() => {
fs.readFile('data.json', 'utf8', (err, data) => {
const allData = JSON.parse(data);
console.log(allData); // IS OK!
return allData;
});
}
}
歡迎來到異步功能的奇妙世界 – George
看看這個主題http://stackoverflow.com/questions/20647346/simple-nodejs-callback-example-with-fs-readfile – Leguest
使用promise來獲取對象 – Tushar