2013-04-02 37 views
7

我新的節點調用Windows API的,我有這個簡單的Node.js服務器適用於Windows從node.js的味精

服務器代碼

var ws = require("websocket-server"); 

var server = ws.createServer(); 

server.addListener("connection", function(client){ 
    console.log("new connection"); 
    client.send("aaaaaa"); 
    client.addListener("message", function(msg){ 
     console.log(msg); 
    }); 
}); 

server.listen(8080); 

我只是想調用Windows API insted的的線

console.log(msg); 

有沒有辦法做到這一點,而無需使用外部庫

什麼想法?

回答

10

我認爲node-ffi可以幫助你做到這一點。 node-ffi提供加載和調用動態庫的功能。通過node-ffi,您可以訪問user32(例如)lib並從node.js調用它們的函數。

var FFI = require('node-ffi'); 

function TEXT(text){ 
    return new Buffer(text, 'ucs2').toString('binary'); 
} 

var user32 = new FFI.Library('user32', { 
    'MessageBoxW': [ 
     'int32', [ 'int32', 'string', 'string', 'int32' ] 
    ] 
}); 

var OK_or_Cancel = user32.MessageBoxW(
    0, TEXT('I am Node.JS!'), TEXT('Hello, World!'), 1 
); 
+0

謝謝,我已經嘗試過了,遺憾的是不工作 「NPM安裝節點FFI」不爲我工作,所以我問是否有任何解決方案,而不使用外部庫 –

+4

據我所知,node-ffi需要python安裝在您的系統上。 Node.js沒有調用winapi函數的本地方法。 –

+2

我已經安裝了它但存在配置錯誤: gyp ERR!配置錯誤 gyp ERR!堆棧錯誤:'gyp'失敗並退出代碼:1 gyp ERR!可以在ChildProcess.onCpExit(C:\ ProgramFiles \ nodejs \ node_modules \ npm \ node_modules \ node-gyp \ lib \ configure.js:415:16)上創建堆棧: 等等...... –

4

我不想編輯@ Vadim的答案,因爲它被接受了,但我認爲該包已被重命名爲'ffi'。這爲我工作:

npm install -s ffi 

而且使用@瓦迪姆的來源,而且改變了包名ffi

var FFI = require('ffi'); 

function TEXT(text){ 
    return new Buffer(text, 'ucs2').toString('binary'); 
} 

var user32 = new FFI.Library('user32', { 
    'MessageBoxW': [ 
     'int32', [ 'int32', 'string', 'string', 'int32' ] 
    ] 
}); 

var OK_or_Cancel = user32.MessageBoxW(
    0, TEXT('I am Node.JS!'), TEXT('Hello, World!'), 1 
);