VSCodeでのNode.jsデバッグ(Windows編)

node
global.module.paths
.exit
npm root -g
>C:\Users\[ユーザー名]\AppData\Roaming\npm\node_modules

環境変数 NODE_PATH に上記を追加

上記のディレクトリでコマンドプロンプトを開き、以下を実行

npm install cheerio

"cheerio"はWebスクレイピングのためのライブラリです(詳細は以下参照)

VSCodeで[Open Folder...]で適当なフォルダを作成・開く

開いたフォルダで[New File]で実行したい.jsファイルを作成

例えば、以下のようなtest.js

function Msg(arg) {
   this.payload = arg
}
var msg = new Msg(0)

msg.page_number = msg.payload
msg.url = `https://mag.osdn.jp/news/page/${msg.page_number}/`

const cheerio = new require('cheerio')

function Article(title) {
   this.title = title
   this.content = ''
   this.datetime = ''
   this.link = ''
}

// get html from msg.url to msg.html
const https = new require('https')
https.get(msg.url, res => {
   //console.log('statusCode:', res.statusCode);
   //console.log('headers:', res.headers);
   let html = '';
   res.on('data', line => html += line);
   res.on('end', () => {
       const $ = cheerio.load(html);
       var articles = []

       $('h2', 'article').each((i, elem) => {
           articles.push(new Article($(elem).text()))
       })
       $('p', 'article').each((i, elem) => {
           articles[i].content = $(elem).text()
       })
       $('time', 'article').each((i, elem) => {
           articles[i].datetime = $(elem).attr('datetime')
       })
       $('a', 'article').each((i, elem) => {
           articles[i].link = $(elem).attr('href')
       })

       articles.forEach( (article) => console.log(article.title));
   });
}).on('error', (e) => {
   console.error(e);
});

Ctrl+Shift+D を押して [create a launch.json file]をクリック
よくわかんないのでデフォルトのままで

後は、F5(デバッグ実行) / F9(指定した行にブレークポイント張る)  / F10(ステップ実行) などができます



この記事が気に入ったらサポートをしてみませんか?