gpt4 book ai didi

node.js - 返回值未定义(应为字符串)

转载 作者:搜寻专家 更新时间:2023-11-01 00:33:38 25 4
gpt4 key购买 nike

我刚开始使用 NodeJS 开发一些东西,但遇到了一个非常令人沮丧的错误。

我有一个函数可以将 .jade 编译成 .html

function compileJadeFile(jadeFile){
var pathToFile = "./index.jade";

fs.exists(pathToFile, function(exists){
if(exists){
fs.readFile(pathToFile, function(err, data){
var html = jade.compile(data)();
return html;
});
}
});
}

一切正常,但现在我想提供编译后的 html。所以我做了这样的事情:

res.write(compileJadeFile("index.jade"));

(不用理会compileJadeFile中没有用到的参数,原来是用的,我只是为了这个例子把它缩短了)

现在,如果我将 compileJadeFile("index.jade") 的结果记录到控制台,它会显示 "undefined" :(

我在谷歌上搜索了这个,但没有找到解决问题的方法。你们中的任何人都可以帮助我吗?我习惯于使用 C# 或 C++ 编写代码,所以我可能遗漏了某些东西或 Javascript 的特殊之处?

最佳答案

您的代码是同步的,但您使用的代码是异步的。问题是,当您调用 compileJadeFile 函数时,它实际上不返回任何内容,因此根据定义,它的返回值是 undefined

您也需要使函数本身异步,并引入回调并将您的方法更改为:

function compileJadeFile(jadeFile, callback) {
var pathToFile = "./index.jade";

fs.exists(pathToFile, function(exists) {
if(exists){
fs.readFile(pathToFile, function(err, data) {
var html = jade.compile(data)();
callback(html);
});
}
});
}

然后你可以像这样使用它:

compileJadeFile("index.jade", function (html) {
res.write(html);
res.end();
});

请注意,对于完全符合 Node.js 的回调,回调始终应将 err 作为其第一个参数来传输错误。因此,理想情况下,您的代码应该是:

compileJadeFile("index.jade", function (err, html) {
if (err) { throw err; }
res.write(html);
res.end();
});

那么,当然你需要把回调的调用改成:

callback(null, html);

希望这有帮助:-)。

关于node.js - 返回值未定义(应为字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742488/

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