小编典典

这个Javascript“要求”是什么?

node.js

我正在尝试让Javascript读取/写入PostgreSQL数据库。我在github上找到了这个项目。我能够获得以下示例代码以在节点中运行。

var pg = require('pg'); //native libpq bindings = `var pg = require('pg').native`
var conString = "tcp://postgres:1234@localhost/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。那是什么意思
我查看了目录,但没有找到文件pg。它放在哪里,以及Javascript如何找到它?


阅读 246

收藏
2020-07-07

共1个答案

小编典典

那么这是什么“要求”?

require()不是标准JavaScript
API的一部分。但是在Node.js中,它是一个内置函数,具有特殊目的:加载模块

模块是一种将应用程序拆分为单独文件的方法,而不是将所有应用程序都包含在一个文件中。其他语言在语法和行为上也存在细微差别,例如C
include,Python import等等,也存在该概念。

Node.js模块和浏览器JavaScript之间的最大区别是如何从另一个脚本的代码访问一个脚本的代码。

  • 在浏览器JavaScript中,脚本是通过<script>元素添加的。当它们执行时,它们都可以直接访问全局范围,即所有脚本之间的“共享空间”。任何脚本都可以在全局范围内自由定义/修改/删除/调用任何内容。

  • 在Node.js中,每个模块都有自己的作用域。一个模块不能直接访问另一个模块中定义的内容,除非它选择公开它们。要公开模块中的内容,必须将其分配给exportsmodule.exports。要使一个模块访问另一个模块的exportsmodule.exports必须使用require()

在您的代码中,var pg = require('pg');加载pg模块,即Node.js的PostgreSQL客户端。这使您的代码可以通过pg变量访问PostgreSQL客户端API的功能。

为什么它在节点中有效但在网页中无效?

require()module.exportsexports是一个模块系统特定于Node.js的的API的 浏览器未实现此模块系统。

另外,在我让它在节点上工作之前,我必须做npm install pg。那是什么意思

NPM是一个软件包存储库服务,用于承载已发布的JavaScript模块。npm install是一个命令,可让您从其存储库中下载软件包。

它放在哪里,以及Javascript如何找到它?

npm cli将所有下载的模块放在node_modules您运行的目录中npm install。Node.js拥有关于模块如何查找其他模块的非常详细的文档,包括查找node_modules目录。

2020-07-07