How to get current directory(current path) using node-webkit

HandyPost means document written by DoYeong Han(HDNua). Feedback is always welcome (includes syntax error. I'm not good at English).

 

1. Preface

Now I'm posting a series of document named "JSCC: Developing C Compiler Using JavaScript". So I looked for information of node.js to access user's local file system, and I found module "node-webkit" let me able to develop GUI program with HTML, CSS and JavaScript.

node.js: https://nodejs.org/

nw.js: http://nwjs.io/

I use Brackets of Adobe.

Brackets: http://brackets.io/

But it was hard to me to get current path using node-webkit. And I searched information a while and I got solution for this problem. Let me explain how to get working directory using nw module.

 

2. Project Preparation

We have to prepare project folder before get the path we want.

2.1) Make project folder. Folder's name should be 'project'.

2.2) Create 2 file and copy these codes. for nw.js application execution.

project/package.json

1
2
3
4
{
  "name""getting current path example",
  "main""index.html"
}
cs

project/index.html

1
2
3
4
5
6
7
<html>
  <body>
    <script>
      alert('hello, world!');
   </script>
  </body>
</html>
cs

This results an alert window shows 'hello, world!' string, and our goal is replacing this string to executing application's current path.

2.3) Check module node.js and node-webkit is installed.

Each program is available from official web site. node.js can be installed easily with official site's installer on Windows OS. node-webkit is provided as binary zip file. Extract it and move created folder to "C:/nwjs". So those 2 folder's full path is same with below.

C:\Users\Administrator\Desktop\project

C:\nwjs

2.4) Set nw.exe program to environment variable.

It requires two steps such below:

2.4.1) Add string "C:\nwjs;" to PATH variable.

2.4.2) Create "nw" variable and set value "C:\nwjs\nw".

When process is finished, check each case have no problems.

- "node" command must be available on command prompt.

- "project" directory should be in Desktop.

- There must be files "index.html", "package.json" in directory "project".

- There must be files extracted from "node-webkit binary" in directory "nwjs".

- "nw" command must be available on command prompt.



Preparation is end. Let's get working directory.

 

3. How to get current directory (running zip file)

node-webkit is based on node.js module. Therefore it is also possible to run node-webkit app using 'node.js' module. I thought that, it is possible to give current path string as arguments when start node-webkit process. Let me explain.

3.1) Compress project folder and rename zip file to 'app.zip'. So 'app.zip' will be in folder 'project'.

3.2) Add 'main.js' file to project folder and copy code below.

project/main.js

1
2
3
4
5
6
7
8
9
// get child_process module.
var childproc = require('child_process');
 
// start process using child_process
//  with current path string
// '__dirname' would be not only path
//  of 'main.js' but also one of 'app.zip'
//  because 'main.js' and 'app.zip' have same directory
childproc.exec('nw app.zip ' + __dirname);
cs

3.3) Run command prompt and change directory to it.

3.4) Enter "node main.js" and check wrote program works well.

Go through steps when program works well. If not, chekc previous steps.

3.5) Modify "index.html" as below.

index.html <html.body.script>

1
2
3
4
5
6
7
8
9
10
// get 'nw.gui' module
var gui = require('nw.gui');
 
// get arguments that we passed
var arr = gui.App.argv;
 
// nw app.zip __dirname
//            ^ argv[0]
alert('current path: [' + arr[0+ ']');
 
cs

3.6) Delete previous zip file (app.zip) and re-compress project folder. Newly created zip file's name must be 'app.zip' too.

3.7) Enter "node main.js" again and see the result.


Finally, we got the current directory.

'알려주기' 카테고리의 다른 글

[JSCC] 7. JSCC 준비  (0) 2015.06.19
Ubuntu Tips  (0) 2015.06.18
노드웹킷(node-webkit)을 이용하여 현재 경로 얻기  (5) 2015.06.15
[JSCC] 이번주 JSCC는 휴재합니다.  (0) 2015.06.08
[JSCC] 6. JavaScript 튜토리얼  (0) 2015.06.05
Posted by 누아니
,

노드웹킷(node-webkit)을 이용하여 현재 경로 얻기

HandyPost는 한 도영(HDNua)이 작성하는 포스트 문서입니다.

 

1. 개요

현재 "JSCC: JavaScript로 개발하는 C Compiler" 강좌를 연재하고 있다. 이를 위해 파일 시스템에 접근하려는 목적으로 node.js를 보고 있는데, HTML, CSS, JavaScript를 이용하여 GUI 프로그램을 개발할 수 있다는 node-webkit이라는 것을 발견하여 공부하고 있었다.

node.js: https://nodejs.org/

nw.js: http://nwjs.io/

개발 도구로는 AdobeBrackets를 사용하고 있다.

Brackets: http://brackets.io/

그런데 노드웹킷을 이용하여 실행 중인 압축 파일의 경로를 얻는 것이 생각보다 쉽지 않았다. 그래서 한참 삽질을 하다가 괜찮은 방법을 알게 되어 이를 소개하고자 한다.

 

2. 프로젝트 준비

실행 중인 압축 파일의 경로를 얻기 전에 프로젝트를 준비하자.

2.1) 프로젝트 폴더를 만든다. project 폴더를 생성한다.

2.2) nw.js 애플리케이션 실행을 위한 기본 파일을 구성한다. 다음 두 파일을 준비하면 된다.

project/package.json

1
2
3
4
{
  "name""getting current path example",
  "main""index.html"
}
cs

project/index.html

1
2
3
4
5
6
7
<html>
  <body>
    <script>
      alert('hello, world!');
    </script>
  </body>
</html>
cs

“hello, world!” 문자열 경고 창이 뜨는 예제인데, 목표는 이 문자열을 경로로 바꾸는 것이다.

2.3) node.jsnode-webkit이 설치되어있는지 확인한다.

두 프로그램 모두 공식 홈페이지에서 내려받을 수 있다. node.jsWindows에서 설치 형태로도 제공되니 이것을 이용하여 설치하자. node-webkit은 바이너리 형태로 제공되는데 압축을 풀면 nw.exe 실행 파일이 포함된 디렉터리가 생성된다. 여기서는 C:\nwjs 폴더에 node-webkit 파일이 있다고 하겠다. 즉 두 폴더의 전체 경로는 각각 다음과 같다.

C:\Users\Administrator\Desktop\project

C:\nwjs

2.4) nw.exe 프로그램을 환경 변수로 등록한다.

이를 위해 다음의 두 과정을 거친다.

2.4.1) PATH 변수에 C:\nwjs;를 추가한다.

2.4.2) 사용자 환경 변수에 nw를 추가하고 값을 C:\nwjs\nw로 설정한다.

작업이 모두 끝나고 나면 다음이 만족되어야 한다.

- 명령 프롬프트에서 node 명령이 통해야 한다.

- 바탕 화면에 project 폴더가 있어야 한다.

- project 폴더에 index.html, package.json 파일이 있어야 한다.

- nwjs 폴더에 node-webkit 압축 파일을 해제한 결과가 있어야 한다.

- 환경 변수가 모두 제대로 등록되어, 명령 프롬프트에서 nw 명령이 통해야 한다.




이제 이를 이용해 파일 경로를 얻는 방법을 알아보자.

 

3. 실행 중인 압축 파일의 경로 획득

node-webkitnode.js를 기반으로 실행되는 모듈이다. 따라서 node-webkit 애플리케이션을 실행하기 위해 node.js를 이용하는 것이 당연히 가능하다. 필자는 node-webkit 프로세스를 실행할 때 인자로 현재 작업 경로를 넘기는 방식으로, 실행 중인 압축 파일의 경로를 획득할 수 있다는 생각을 했다. 어떻게 하는지 알아보자.

3.1) project 폴더를 압축하여 app.zip 파일을 생성한다. app.zipproject 폴더 안에 있게 된다.

3.2) 프로젝트 폴더에 main.js 파일을 추가하고 다음과 같이 파일을 작성한다.

project/main.js

1
2
3
4
5
6
7
8
// child_process 모듈을 획득합니다.
var childproc = require('child_process');
 
// child_process 모듈을 이용하여 현재 실행중인 코드의 경로를 획득합니다.
// app.zip의 경로와 main.js의 경로가 같으므로
// __dirname이 main.js의 경로가 되면서 app.zip의 경로가 됩니다.
childproc.exec('nw app.zip ' + __dirname);
 
cs

3.3) 명령 프롬프트를 실행하고 프로젝트 폴더로 이동한다.

3.4) node main.js 명령을 입력하여 프로그램을 실행하여 제대로 동작하는지 확인한다.

정상 동작함을 확인했다면 창을 닫는다. 오류가 발생한다면 과정을 다시 확인하라.

3.5) index.html을 다음과 같이 수정하고 저장한다.

index.html <html.body.script>

1
2
3
4
5
6
7
8
9
// nw.gui 모듈을 가져옵니다.
var gui = require('nw.gui');
 
// nw 프로그램을 실행할 때 넘긴 인자를 획득합니다.
var arr = gui.App.argv;
 
// nw app.zip __dirname
//            ^ argv[0]
alert('current path: [' + arr[0+ ']');
cs

3.6) 압축 파일은 수정되지 않았으므로, 이전 압축 파일을 삭제하고 새롭게 압축한다.

이때도 압축 파일의 이름은 app.zip이어야 한다.

3.7) node main.js 명령을 다시 실행하여 결과를 확인한다.


이와 같이 현재 경로를 획득할 수 있었다.

Posted by 누아니
,








ipTime N604M이던가.

안테나 하나 달려있던 공유기를 한참을 쓰고 있다가

방 안에 있어서 그런지 와이파이도 안 터지고 해서

그저께 새 공유기를 주문했다.


가격은 19,770원. 전원 콘센트가 포함되어있는데 이 정도면 적당한 가격이다.

하나는 방 안에, 하나는 거실에 설치했다.


공유기를 2개 설치하려고 보니 처음엔 잘 안 되더라.

인터넷에 찾아보니 IP가 충돌하기 때문이라고.

해법은 여기 있으니 참고하면 좋다.

http://blog.copierrental.net/220257272021

'생각' 카테고리의 다른 글

링피트 하나 더 샀다.  (0) 2021.01.01
Stan Lee  (0) 2018.11.13
iPhone 6S 발표!  (0) 2015.09.10
페이스북 계정 비활성화했다.  (0) 2015.08.11
JSCC 연재가 끝났다.  (2) 2015.07.31
Posted by 누아니
,