[英]Gatsby Node API onPostBuild in gatsby-node.js unable to execute
module.exports = { parseXML: function(file_path, callback) { callback("test 1") readFile(file_path.toString(), "utf-8", function(err, data) { if (err) callback(err); parseString(data, function(err, result) { if (err) callback(err); callback("test 2") var json = result; delete json.sitemapindex.sitemap[1].lastmod; var builder = new xml2js.Builder(); var xml = builder.buildObject(json); write2File(file_path.toString(), xml, function(err, data) { if (err) callback(err); callback("test 3") callback("successfully written our update xml to ",file_path.toString()); }); }); }); callback("test 4") } }
This is a function to parse XML to JSON and modify the JSON and write back to XML. This is a function to parse XML to JSON and modify the JSON and write back to XML. I called this function in
gatsby-node.js
in onPostBuild
like this我在
onPostBuild
的gatsby-node.js
中这样称呼这个 function
exports.onPostBuild = async () => {sitemap_mod.parseXML("filename")}
However, in the gatsby build
, it only printed out test:1
and test:4
, which means it failed to execute anything in the readFile function.但是,在
gatsby build
中,它只打印出test:1
和test:4
,这意味着它无法执行 readFile function 中的任何内容。 I suppose this is because the onPostBuild
is an async function and I need to add some await
state in my code.我想这是因为
onPostBuild
是异步 function ,我需要在我的代码中添加一些await
state 。 I applied this function in other node API such as onPostBootstrap
and onCreateDevServer
and they were both working properly, able to execute readFile
and write2File
function.我在其他节点 API 中应用了这个 function,例如
onPostBootstrap
和onCreateDevServer
,它们都工作正常,能够执行readFile
和write2File
ZC1C425268E68385D14AB5074C17A。 So I think there's something wrong about my usage of onPostBuild
.所以我认为我对
onPostBuild
的使用有问题。 Thanks for your help!谢谢你的帮助!
Yes, you should indeed make sure to wait for the function to finish.是的,您确实应该确保等待 function 完成。
You need to wait for the three asynchronous calls you have inside parseXML
.您需要等待
parseXML
内部的三个异步调用。 I usually use promisify
to turn them into async functions:我通常使用
promisify
将它们变成异步函数:
const { promisify } = require("util");
const asyncParseString = promisify(parseString);
const asyncReadFile = promisify(readFile);
const asyncWrite2File = promisify(write2File);
function transformJsonToXml(json) {
...
}
async function parseXML(file_path) {
const data = await asyncReadFile(file_path.toString(), "utf-8");
const json = await asyncParseString(data);
await asyncWrite2File(file_path.toString(), transformJsonToXml(json));
}
Your onPostBuild
then needs to wait for parseXML
to finish.然后您的
onPostBuild
需要等待parseXML
完成。 So either put an await
before the parseXML
call or just use所以要么在
parseXML
调用之前放置一个await
,要么只使用
exports.onPostBuild = () => sitemap_mod.parseXML("filename")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.