node.js - 使用 Node.js 在 HTTP 请求中打印模块响应,基本问题
问题描述
我从未使用过 node.js(仅 PHP),但找到了一个 node 模块,但我已经尝试解决这个问题 3 个小时了。
我使用这个模块:Play Scraper
他们使用此代码运行它,这在 SSH 控制台上运行良好
var gplay = require('google-play-scraper');
gplay.app({appId: 'com.google.android.apps.translate'})
.then(console.log, console.log);
但是我想将它作为 HTTP 服务器运行并在那里以 JSON 格式打印响应,这是我的代码:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write("hello!\n");
var gplay = require('google-play-scraper');
gplay.app({appId: 'com.google.android.apps.translate'}).then(
result => {
res.write(result);
}
)
res.write("bye!\n");
res.end();
});
server.listen(8080);
console.log('server running on port 8080');
我只得到“你好”和“再见”之间什么都没有。我意识到这个问题可能是因为我想在里面获得模块响应。如果我在 server.listen(8080) 之前播放 gplay.app 并转到 console.log 它在 SSH 中效果很好。
如何在屏幕上打印 gplay.app 响应(JSON.stringify),现在问题出在哪里?
谢谢!
解决方案
关于使用 JavaScript,您需要考虑几件事情。除非指定,否则您所做的任何 IO 操作通常都是非阻塞的。当使用回调或then
(称为 Promise)时,代码在继续下一条语句之前不会等待任何回调。近年来的 JavaScript 使用 async await 语法糖使这更容易理解。
修复代码的最佳方法是实现此异步等待语法:
const http = require('http');
// Best practice to import everything at the start
const gplay = require('google-play-scraper');
const server = http.createServer(async (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write("hello!\n");
// the result will be "awaited" and then written into the response.
res.write(await gplay.app({appId: 'com.google.android.apps.translate'});
res.write("bye!\n");
res.end();
});
server.listen(8080);
console.log('server running on port 8080');
但是,要了解为什么您的解决方案不起作用,让我们逐步检查您的代码
http.createServer((req, res) => {
// Write operations (to a buffer, which is what this response object is)
// are not asynchronous. You do not need to wait for a response
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write("hello!\n");
var gplay = require('google-play-scraper');
// Calling ".then" means waiting for the result to complete and issuing
// your given `res.write` once the response has been provided.
gplay.app({appId: 'com.google.android.apps.translate'}).then(
result => {
// if we only write the next part of the response
// once our result has been fetched, then the writes
// will occur in the correct order
res.write(result);
res.write("bye!\n");
// and your "end" will fire after your response has been written
res.end();
}
)
});
希望这可以帮助您更好地理解。
推荐阅读
- python - 特征缩放产生所有 NaN 值
- html - Bootstrap,让两个元素交换边
- django - 使用 Dockerized Django 和 RDS 的最佳实践是什么?
- php - 重新映射控制器时使用默认数组
- python - PyTest生成的html报告的测试用例如何重命名
- jupyter - 如何将jupyter笔记本转换为幻灯片
- python - 将 sqlite 参数从另一个 python 代码传递到 python 代码
- java - Java数组在范围内时抛出空指针
- python - Discord self bot 仅将我的帐户作为具有多个成员的公会成员返回
- javascript - 如何在 atom 编辑器中运行 javascript 文件?