파일 업로드/다운로드
현재 자바스크립트로 실행 환경을 만들고 있다. IPFS 라이브러리를 이용해야한다.
실행 환경은 2가지로 분류된다.
런타임 환경 : Node.js로 자바스크립트를 실행하는 환경, ipfs-api 라이브러리, 일반적으로 npm 사용
웹 브라우저 환경 : 웹 브라우저에서 자바스크립트를 실행하는 환경, ipfs-http-client 라이브러리, npm 으로 설치가 가능하나 일반적으로 CDN 사용
런타임 환경을 npm으로 두 라이브러리를 설치해 구축해보자.
Node.js, Git, 몇가지 파일이 필요하다
ipfs init <- 한번 했으면 안해도 됨
ipfs daemon <- 백그라운드로 프로세스 실행
데몬을 실행 시킨 cmd는 최소화 후 새로운 cmd 열기
npm install --save ipfs-api <- ipfs-api 라이브러리 설치 @26.1.2
npm install --save ipfs-http-client@56.0.2 <- ipfs-http-client 라이브러리 설치
// test.txt
Hello, IPFS
여기선 node [파일명] 명령어로 실행시켜 결과를 확인한다.
업로드
// ipfs_api_upload_sample.js
const IPFS = require('ipfs-api');
const fs = require('fs');
// IPFS 노드 정보
// IPFS 데몬을 실행한 결과에서 'API Server' 정보를 입력합니다.
const ipfs = new IPFS({
host : 'localhost',
port : 5001,
protocol : 'http'
});
const file = fs.readFileSync('./test.txt')
const fileBuffer = new Buffer.from(file);
ipfs.files.add(fileBuffer, (err, f) => {
console.log(f);
});
// ipfs_api_http_client_upload_sample.js
const IpfsHttpClient = require('ipfs-http-client');
const fs = require('fs');
const ipfs = IpfsHttpClient.create(); // default 'http://localhost:5001'
async function main() {
const file = fs.readFileSync('./test.txt');
let rst = await ipfs.add(file);
console.log(rst);
}
main();
ipfs-api 라이브러리로 test.txt가 업로드 되어 위와 같은 결과를 받았다.
path : 업로드한 파일의 경로
hash : 업로드한 파일의 해시
size : 파일의 크기, 단위는 Byte
hash는 다운로드 때 사용하므로 따로 기록하자
이번엔 ipfs-http-client 라이브러리이다
ipfs-http-client 라이브러리를 사용했다
apth : 경로
cid : 콘텐츠 식별자
size : 파일용량
WebUI에서 해시를 검색하면 업로드한 파일의 내용을 확인할 수 있다. ( http://localhost:5001/webui )
다운로드
// ipfs_api_download_sample.js
const IPFS = require('ipfs-api');
const ipfs = new IPFS({
host : 'localhost',
port : 5001,
protocol : 'http'
});
const hash = '업로드 때 받은 해시';
ipfs.files.get(hash, (err, ff) => {
console.log(ff[0].content.toString());
});
// ipfs_api_http_client_download_sample.js
const IpfsHttpClient = require('ipfs-http-client');
const ipfs = IpfsHttpClient.create('http://localhost:5001'); // default 'http://localhost:5001'
async function main() {
const chunks = [];
const path = '업로드 때 받은 패스'
for await (const chunk of ipfs.cat(path)){
chunks.push(chunk);
};
console.log(chunks.toString());
};
main();
다운로드 결과를 확인해보자
위는 ipfs-api 라이브러리, 아래는 ipfs-http-client 라이브러리이다.
추가
이미 공개된 메인 네트워크에 IPFS를 연결하면 로컬 환경에 실행하지 않더라도 IPFS를 이용할 수 있다. 메인 네트워크의 웹 탐색기는 다음 사이트에서 확인할 수 있으며 메인 네트워크에 연결하고 싶다면 다음과 같이 작성하면 된다.
- 메인 네트워크의 웹 탐색기 : https://explore.ipld.io
const ipfs = IpfsHttpClient.create('https://ipfs.infura.io:5001');