什么是这个Javascript“需要”? [英] What is this Javascript "require"?

查看:93
本文介绍了什么是这个Javascript“需要”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让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();

//连接可用时,查询将排队并一个接一个执行
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)

//查询可以通过作为单独参数传递的文本/参数值执行
//或通过传递包含文本,(可选)参数值和(可选)查询的选项对象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)]
});

//使用相同名称的后续查询将被执行,而不需要通过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']);

//可以将行结果一次返回1个
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()); //日期作为javascript日期返回
console.log(Beatle height:%d'%d\,Math.floor(row.height / 12),row.height%12); //整数被返回为javascript ints
});

//最后一行被触发后被触发
query.on('end',function(){
client .end();
});



接下来我试图让它运行在



那么这个require是什么呢?为什么呢?

此外,在我在节点上工作之前,我不得不做 npm install pg

code>这是什么?我在目录中查找,没有找到一个文件pg。它放在哪里,Javascript怎么找到呢?

解决方案

require()不是您的标准JavaScript的一部分。在您的问题和标签的上下文中, require()内置在Node.js中以加载模块。这个概念类似于C / Java / Python / [在这里插入更多语言]导入或包含。



模块的概念类似于只添加一小部分JavaScript代码通过< script> 标记。与添加< script> 标记不同,它不会将文件泄漏到全局范围。该文件有自己的作用域,基本上会捕获您在该文件中定义的所有内容,除非您决定公开功能。 require 返回一个值,取决于模块使用 exports module.exports 另一篇帖子介绍了 require()如何与 exports 。



在您的代码中,它加载 pg ,我猜是一个用于NodeJS的PostgreSQL驱动程序。你所做的 npm install pg 从npm(NodeJS模块的软件包存储库)下载 pg 它可通过 require('pg');

$





为了防止你想知道为什么我在上下文中提到你的问题,有第三方库也使用一个名为 require 的函数来做某事。非常方便识别哪个是。




  • RequireJS 暴露一个名为 require 的函数以及 define 加载依赖关系在运行之前提供的代码。语法为AMD格式。


  • Neuter (它连接js文件)还公开了一个名为 require 的函数。这个操作更接近PHP的 import


  • Browserify 在浏览器上使用 require ,允许在浏览器上编写NodeJS样式(CommonJS模块语法)。



I'm trying to get Javascript to read/write to a PostgreSQL database. I found this project on github. I was able to get the following sample code to run in node.

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();
});

Next I tried to make it run on a webpage, but nothing seemed to happen. I checked on the Javascript console and it just says "require not defined."

So what is this "require?" Why does it work in node but not in a webpage?

Also, before I got it to work in node, I had to do npm install pg. What's that about? I looked in the directory and didn't find a file pg. Where did it put it, and how does Javascript find it?

解决方案

require() is not part of your standard JavaScript. In context to your question and tags, require() is built into Node.js to load modules. The concept is similar to C/Java/Python/[insert more languages here] imports or includes.

The concept of modules is similar to just adding small bits of JavaScript code via a <script> tags. Unlike adding a <script> tag, it doesn't leak the file into the global scope. The file has its own scope, essentially trapping everything you define in that file, unless you decide to expose functionality. require returns a value, depending on what the module exposes using exports or module.exports. Another post explains how require() works in conjunction with exports.

In your code, it loads the pg module, which I guess is a PostgreSQL driver for NodeJS. The part where you do npm install pg downloads the pg module from npm (a package repository for NodeJS modules) and makes it available to your project via require('pg');.


Just in case you were wondering why I mentioned "in context to your question", there are 3rd-party libraries that also use a function named require to do something. It's handy to identify which is which.

  • RequireJS exposes a function called require, along with define to load dependencies before running the code provided. The syntax is in AMD format.

  • Neuter, which concatenates js files, also exposes a function named require. This one acts much closer to PHP's import.

  • Browserify uses require on the browser, allowing scripts on the browser to be written NodeJS style (CommonJS module syntax).

这篇关于什么是这个Javascript“需要”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆