gpt4 book ai didi

javascript - 调用 Node 模块时未定义不是函数

转载 作者:行者123 更新时间:2023-11-28 19:10:54 26 4
gpt4 key购买 nike

我已将一些逻辑分离到项目中的不同文件中,问题是我收到以下错误

Cannot read property 'readFile' of undefined

这是我的项目的结构

projName
utils
file.js

file.js 代码是

module.exports = function () {
var fs = require('fs');
function readFile(filePath) {
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
return console.log("error to read file: " + filePath + " " + err);
}
return data;
});
}
};

我想调用此模块

projname
controller
request

我用下面的代码来实现这里我得到了错误

   module.exports = function (app) {
app.get('/test', function(req, res) {

var file = require('../utils/file')();
var fileContent = file.readFile("C://test.txt");

知道我在这里做错了什么吗?这与异步调用无关

最佳答案

你的 file.js 可能是这样的:

var fs = require('fs');

module.exports.readFile = function (filePath, cb) {
fs.readFile(filePath, 'utf8', cb);
};

你的 request.js 文件如下:

var file = require('../utils/file');

module.exports = function (app) {

var fileContent = '';
var filePath = 'C://test.txt';

file.readFile(filePath, function (err, data) {
if (err) {
return console.log("error to read file: " + filePath + " " + err);
}

console.log(data);
fileContent = data;
});

// some content

}

关于异步调用当您从 Node.JS 库调用方法时,它通常是异步调用,这意味着函数的结果不会立即返回:

var data = fs.readFile(filePath);

相反,它会在稍后的某个时间返回,因此稍后获取结果的唯一方法是传递一个将在结果准备好时调用的函数:

fd.readFile(filePath, function dataReady (err, data) {
console.log(data)
});

关于 module.exports 当您导出在 Node.JS 中创建的文件的某些逻辑时,您可以通过以下方式返回您的函数:

// exporting a function, myModule.js
module.exports = function () {
console.log('hello');
};

// consuming myModule.js
var someFunction = require('./myModule.js');
someFunction(); // prints 'hello';
<小时/>
// exporting a function, myModule.js
module.exports.readFile = function () {
console.log('hello');
};

// consuming myModule.js
var myModule = require('./myModule.js');
myModule.readFile(); // prints 'hello';

更新:在 file.js 中,您将导出一个函数,该函数将接收文件路径和一个名为回调的函数作为第二个参数(是的,您读得很好,函数作为参数),一旦 fs 被调用,该函数将被调用.readFile 获取文件内容。

module.exports.readFile = function (filePath, callback) {
fs.readFile(filePath, 'ut8', function (err, fileContent) {
callback(err, fileContent);
});
}

然后在您的 request.js 文件中,您正在使用刚刚创建的模块 (file.js),并且您的模块导出的函数接受一个名为 filePath 的字符串作为参数,以及一个名为回调的函数作为参数: file.readFile(filePath, 回调)

因此,当您的模块 file.js 获取内容文件时,将调用您的回调函数参数。

var file = require('../utils/file');

file.readFile(filePath, function (err, data) {
if (err) {
return console.log("error to read file: " + filePath + " " + err);
}

console.log(data);
fileContent = data;
});

我希望这有助于澄清您对回调的一些了解。

关于javascript - 调用 Node 模块时未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734794/

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