05-02 20:56
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[WebApp / Node Webkit] Example 4 - Using Node.JS File System 본문

Programming/Web App

[WebApp / Node Webkit] Example 4 - Using Node.JS File System

cinema4dr12 2016. 1. 27. 22:50



이번 글에서는 Node-Webkit에서 Node.JS의 File System(fs)을 활용한 예제를 소개하도록 하겠다. 본 예제는 지정된 경로 내의 폴더들 및 파일들을 리스트 형식으로 보여주는 것이다.


Codes

package.json:

{ "name": "file system", "main": "index.html", "window": { "toolbar": false } }


index.html:

<!DOCTYPE html> <html> <head> <title>Show Files</title> </head> <script> var fs = require('fs'); var path = 'C:/'; var ulTag = document.createElement('ul'); function generateListTagItem(file) { var liTag = document.createElement('li'); liTag.textContent = file; ulTag.appendChild(liTag); } function readFilesInPath() { var bodyTag = document.getElementsByTagName('body')[0]; fs.readdir(path, function(err, files) { if(err) throw err; files.forEach(generateListTagItem); bodyTag.appendChild(ulTag); }); } </script> <body> <h1>Files in the path</h1> <a href="#" onclick="readFilesInPath();">Show me the files in the path.</a> </body> </html>


var fs = require('fs');


Node.js의 filesystem 라이브러리를 로딩한다.


var ulTag = document.createElement('ul');

function generateListTagItem(file) {
    var liTag = document.createElement('li');
    liTag.textContent = file;
    ulTag.appendChild(liTag);
}


<ul> 태그를 생성하고 generateListTagItem() 함수에서 <li> 태그를 자식 태그로 붙인다.


function readFilesInPath() {
    var bodyTag = document.getElementsByTagName('body')[0];
    
    fs.readdir(path, function(err, files) {
        if(err) throw err;
        
        files.forEach(generateListTagItem);
        
        bodyTag.appendChild(ulTag);
    });
}


readFileInput() 함수를 호출하면 <body> 태그에 generateListTagItem() 함수를 통해 생성된 아이템들을 붙인다. 이 아이템들은 지정된 경로(여기서는 C 드라이브)의 폴더 및 파일들을 의미한다.

Results

Windows 환경에서 실행한 화면 예는 다음과 같다.



물론 Windows 외에 Linux나 Mac OS에서도 동일한 코드로 경로 내 폴더들을 보여 주는 기능이 가능하다. 단, 지정된 경로가 해당 OS에서 유효한지는 확인해야 한다. 예를 들어,  Mac OS에서는 다음의 경로에 있는 파일들을 보여줄 수 있도록 코드를 수정할 수 있다.


index.html:

<!DOCTYPE html> <html> <head> <title>Show Files</title> </head> <script> var fs = require('fs'); var path = '/Users/gchoi/Documents/WebApp/Examples/node-webkit/'; var ulTag = document.createElement('ul'); function generateListTagItem(file) { var liTag = document.createElement('li'); liTag.textContent = file; ulTag.appendChild(liTag); } function readFilesInPath() { var bodyTag = document.getElementsByTagName('body')[0]; fs.readdir(path, function(err, files) { if(err) throw err; files.forEach(generateListTagItem); bodyTag.appendChild(ulTag); }); } </script> <body> <h1>Files in the path</h1> <a href="#" onclick="readFilesInPath();">Show me the files in path.</a> </body> </html>



Mac에서 실행한 실행 화면의 예는 위와 같다.



Comments