[英]What is the syntax to using await and async in asynchronous functions using nodejs?
[英]Nodejs: download a file into string via http, using async await syntax
您可以使用内置的http.get()
并且在 nodejs http doc中有一个示例。
http.get('http://nodejs.org/dist/index.json', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
此示例假定 JSON 内容,但您可以更改end
事件处理程序中的过程以仅将rawData
视为文本并将 json contentType 的检查更改为您期望的任何类型。
仅供参考,这是一些较低级别的代码,我通常不会使用。 如果您真的不想使用第三方库,您可以将它封装在您自己的 function 中(也许用 promise 包裹),但大多数人为此目的使用更高级别的库,这只会使编码更简单。 我通常使用got()
来处理这样的请求,并且这里有一个其他库的列表(都是基于 promise 的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.