这个Javascript“要求”是什么?

JavaScript

西门卡卡西

2020-03-12

我正在尝试让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如何找到它?

第1283篇《这个Javascript“要求”是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
十三小哥Jim 2020.03.12

我注意到,尽管其他答案解释了要求是什么,并且该答案用于在Node中加载模块,但它们并未对在浏览器中工作时如何加载节点模块给出完整的答复。

这很简单。如描述的那样,使用npm安装模块,模块本身将位于通常称为node_modules的文件夹中。

现在,将其加载到您的应用程序中的最简单方法是使用指向该目录的脚本标记从html引用它。也就是说,如果您的node_modules目录位于项目的根目录中,并且位于与index.html相同的级别,则可以在index.html中编写:

<script src="node_modules/ng"></script>

现在,整个脚本将被加载到页面中-因此您可以直接访问其变量和方法。

还有其他在大型项目中使用更广泛的方法,例如require.js之类的模块加载器在这两个中,我没有使用Require my,但是我认为许多人认为它是可行的方式。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android