본문 바로가기

언어/Node.js

[ Node.js ] 간단한 웹 스파이더 작성하기

반응형

 

 

 

Node.js의 비동기 함수를 사용하여 및 Network과 파일 시스템과 동작하는 방법에 대해서 이해를 높이기 위해서 작은 프로그램을 만들어 보고자 합니다.

Node.js를 사용하여 웹 URL을 입력받고, 해당 URL의 내용을 로컬 파일에 저장하는 간단한 콘솔 애플리케이션을 만들어보겠습니다. 이 애플리케이션은 Node.js의 HTTP 모듈과 파일 시스템 모듈을 활용하여 URL에서 데이터를 가져오고 이를 파일로 저장하는 기능을 구현합니다.

단계별 가이드

  1. 프로젝트 설정 및 준비
  2. 필요한 모듈 가져오기
  3. URL 입력 받기
  4. URL에서 데이터 가져오기
  5. 데이터를 파일로 저장하기
  6. 애플리케이션 실행 및 테스트

1. 프로젝트 설정 및 준비

먼저, 프로젝트를 위한 새 디렉토리를 만들고, 해당 디렉토리로 이동한 후 기본 package.json 파일을 생성합니다.

mkdir url-saver
cd url-saver
npm init -y

이 명령어는 url-saver라는 디렉토리를 생성하고, 기본적인 Node.js 프로젝트 설정을 담고 있는 package.json 파일을 생성합니다.

2. 필요한 모듈 가져오기

프로젝트에서 사용할 모듈들을 불러옵니다. HTTP(S) 요청을 처리하기 위해 http 또는 https 모듈을 사용할 것이며, 파일 시스템 작업을 위해 fs 모듈을 사용할 것입니다. 또한, 사용자 입력을 처리하기 위해 readline 모듈을 사용합니다.

const http = require('http');
const https = require('https');
const fs = require('fs');
const readline = require('readline');

3. URL 입력 받기

readline 모듈을 사용하여 콘솔에서 사용자가 입력한 URL을 받아올 수 있습니다. 다음 코드는 사용자의 입력을 받아서 URL을 변수에 저장합니다.

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

// URL 입력 받기
rl.question('Enter the URL: ', (url) => {
    // 입력 받은 URL 사용
    console.log(`Fetching content from: ${url}`);

    // URL에서 데이터 가져오기 및 파일로 저장하기
    fetchDataAndSaveToFile(url);

    rl.close();
});

4. URL에서 데이터 가져오기

사용자가 입력한 URL에서 데이터를 가져오려면 http 또는 https 모듈을 사용해야 합니다. URL이 http 또는 https인지에 따라 적절한 모듈을 선택해야 합니다.

function fetchDataAndSaveToFile(url) {
    const protocol = url.startsWith('https') ? https : http;

    protocol.get(url, (response) => {
        if (response.statusCode !== 200) {
            console.error(`Failed to get '${url}'. Status code: ${response.statusCode}`);
            response.resume(); // Consume response data to free up memory
            return;
        }

        let data = '';

        // 데이터를 받을 때마다 'data' 이벤트 발생
        response.on('data', (chunk) => {
            data += chunk;
        });

        // 데이터 수신이 완료되면 'end' 이벤트 발생
        response.on('end', () => {
            console.log('Data fetched successfully.');
            saveToFile('output.txt', data);
        });
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
    });
}

이 코드는 URL에서 데이터를 가져오는 fetchDataAndSaveToFile 함수를 정의합니다. http 또는 https 모듈의 get 메서드를 사용하여 데이터를 가져오고, 가져온 데이터를 하나의 문자열로 합칩니다.

5. 데이터 파일로 저장하기

가져온 데이터를 로컬 파일에 저장하는 saveToFile 함수를 정의합니다.

function saveToFile(filename, data) {
    fs.writeFile(filename, data, 'utf8', (err) => {
        if (err) {
            console.error(`Failed to write to file '${filename}': ${err.message}`);
            return;
        }
        console.log(`Data saved to file '${filename}' successfully.`);
    });
}

이 함수는 파일 이름과 데이터를 인수로 받아, fs.writeFile 메서드를 사용하여 데이터를 파일에 저장합니다.

6. 전체 코드 예제

모든 코드를 하나의 파일 (app.js)로 통합하여, 최종 코드를 아래와 같이 작성합니다.

const http = require('http');
const https = require('https');
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Enter the URL: ', (url) => {
    console.log(`Fetching content from: ${url}`);
    fetchDataAndSaveToFile(url);
    rl.close();
});

function fetchDataAndSaveToFile(url) {
    const protocol = url.startsWith('https') ? https : http;

    protocol.get(url, (response) => {
        if (response.statusCode !== 200) {
            console.error(`Failed to get '${url}'. Status code: ${response.statusCode}`);
            response.resume();
            return;
        }

        let data = '';

        response.on('data', (chunk) => {
            data += chunk;
        });

        response.on('end', () => {
            console.log('Data fetched successfully.');
            saveToFile('output.txt', data);
        });
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
    });
}

function saveToFile(filename, data) {
    fs.writeFile(filename, data, 'utf8', (err) => {
        if (err) {
            console.error(`Failed to write to file '${filename}': ${err.message}`);
            return;
        }
        console.log(`Data saved to file '${filename}' successfully.`);
    });
}

7. 애플리케이션 실행 및 테스트

이제 코드를 작성한 후, app.js 파일을 저장하고, 터미널에서 다음 명령어로 애플리케이션을 실행할 수 있습니다.

node app.js

애플리케이션을 실행하면 "Enter the URL:" 메시지가 표시됩니다. 원하는 웹 URL을 입력하고 Enter 키를 누르면, 해당 URL의 내용이 output.txt 파일에 저장됩니다.

예를 들어, https://www.example.com을 입력하면, 해당 웹 페이지의 내용이 output.txt 파일에 저장됩니다.

8. 요약

이 간단한 콘솔 애플리케이션은 다음과 같은 작업을 수행합니다:

  1. Node.js 모듈(http, https, fs, readline)을 사용하여 필요한 기능을 구현합니다.
  2. 콘솔에서 사용자 입력을 받아 URL을 입력받습니다.
  3. URL에서 데이터를 가져오고, 이를 로컬 파일에 저장합니다.

이 과정은 Node.js의 기본 기능을 사용하여 비동기적으로 데이터를 처리하고, 파일 시스템과 상호작용하는 방법을 보여줍니다.

반응형