我試圖讓Javascript讀/寫PostgreSQL數據庫。我在github上發現了這個project。我能夠得到以下示例代碼在節點中運行。什麼是Javascript的「要求」?
var pg = require('pg'); //native libpq bindings = `var pg = require('pg').native`
var conString = "tcp://postgres:[email protected]/postgres";
var client = new pg.Client(conString);
client.connect();
//queries are queued and executed one after another once the connection becomes available
client.query("CREATE TEMP TABLE beatles(name varchar(10), height integer, birthday timestamptz)");
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['Ringo', 67, new Date(1945, 11, 2)]);
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['John', 68, new Date(1944, 10, 13)]);
//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
name: 'insert beatle',
text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
values: ['George', 70, new Date(1946, 02, 14)]
});
//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
name: 'insert beatle',
values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['John']);
//can stream row results back 1 at a time
query.on('row', function(row) {
console.log(row);
console.log("Beatle name: %s", row.name); //Beatle name: John
console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
console.log("Beatle height: %d' %d\"", Math.floor(row.height/12), row.height%12); //integers are returned as javascript ints
});
//fired after last row is emitted
query.on('end', function() {
client.end();
});
接下來我試圖讓它在網頁上運行,但似乎沒有發生任何事情。我檢查了Javascript控制檯,它只是說「不需要定義」。
那麼這是什麼「要求?」爲什麼它在節點中工作,而不是在網頁中工作?
而且,之前我把它在節點的工作,我不得不這樣做npm install pg
。那是什麼?我在目錄中查找並沒有找到一個文件頁。它把它放在哪裏,Javascript如何找到它?
require不是javascript的一部分,它是nodejs中使用的關鍵字。 nodejs不是您使用客戶端的DOM。因此,可能適用於nodejs的腳本可能無法在瀏覽器中使用。你可以在nodejs中調用window或document嗎?不,與瀏覽器要求相同。 – mpm 2012-03-28 05:15:25
如何更改上面的代碼,以便它可以在瀏覽器中工作? – neuromancer 2012-03-28 05:25:08
你不能直接從網頁與Pg交談;你需要能夠打開一個簡單的TCP/IP套接字,你可以發送和接收二進制數據,而且沒有網頁瀏覽器會讓你這樣做。您所指的庫是node.js的擴展,並且不適用於客戶端JavaScript。我強烈建議您通過Web服務器和JSON請求/回覆從客戶端與您的PostgreSQL服務器通信。 – 2012-03-28 05:44:51