本日のお題:コンピュータにさせる事は、頼み方次第
以下のコードは、
TypeScript で指定した URL のソースを取り出すサンプル。
import { HttpClient, HttpResponse } from 'http';
async function fetchUrl(url: string): Promise<string> {
const httpClient = new HttpClient();
const response: HttpResponse<string> = await httpClient.get(url, { responseType: 'text' });
if (response.status === 200) {
return response.body;
} else {
throw new Error(`Failed to fetch URL: ${url}. Status code: ${response.status}`);
}
}
(async () => {
const url = 'https://www.example.com';
const source = await fetchUrl(url);
console.log(source);
})();
ーーーーー
上記のソースが動く環境を構築するヒント
なお、実行環境は Windows で
コマンドプロンプトからの実行です。
1.node.jsのインストール
2.npm install -g typescript
3.npm install -g @angular/cli@latest
上記のソースを main.ts として保存したら
コンパイルして実行します。
4.コンパイル
npx tsc main.ts
5.実行ファイルを動かす
node main.js