我试图让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