本文翻译自:What is this Javascript “require”?

I'm trying to get Javascript to read/write to a PostgreSQL database. 我正在尝试让Javascript读取/写入PostgreSQL数据库。 I found this project on github. 我在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: Johnconsole.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript datesconsole.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." 我在Javascript控制台上进行了检查,它只显示“要求未定义”。

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 . 另外,在我让它在节点上工作之前,我必须做npm install pg What's that about? 那是什么意思 I looked in the directory and didn't find a file pg. 我查看了目录,但没有找到文件pg。 Where did it put it, and how does Javascript find it? 它放在哪里,以及Javascript如何找到它?


#1楼

参考:https://stackoom.com/question/fXis/这个Javascript-要求-是什么


#2楼

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser. 我注意到,尽管其他答案解释了要求是什么,并且该答案用于在Node中加载模块,但它们并未对在浏览器中工作时如何加载节点模块给出完整的答复。

It is quite simple to do. 这很简单。 Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules. 如描述的那样,使用npm安装模块,模块本身将位于通常称为node_modules的文件夹中。

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. 现在,将其加载到应用程序中的最简单方法是使用指向该目录的脚本标记从html引用它。 ie if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html: 例如,如果您的node_modules目录位于项目的根目录中,并且位于与index.html相同的级别,则可以在index.html中编写:

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

That whole script will now be loaded into the page - so you can access its variables and methods directly. 现在,整个脚本将被加载到页面中-因此您可以直接访问其变量和方法。

There are other approaches which are more widely used in larger projects, such as a module loader like require.js . 在大型项目中还有其他更广泛使用的方法,例如require.js之类的模块加载器。 Of the two, I have not used Require myself, but I think it is considered by many people the way to go. 在这两个中,我没有使用Require self,但是我认为许多人认为它是可行的方式。


#3楼

You know how when you are running JavaScript in the browser, you have access to variables like "window" or Math? 您知道在浏览器中运行JavaScript时如何访问“窗口”或“数学”等变量吗? You do not have to declare these variables, they have been written for you to use whenever you want. 您不必声明这些变量,而是已编写它们供您随时使用。

Well, when you are running a file in the Node.js environment, there is a variable that you can use. 好吧,当您在Node.js环境中运行文件时,可以使用一个变量。 It is called "module" It is an object. 它称为“模块”。它是一个对象。 It has a property called "exports." 它具有一个称为“出口”的属性。 And it works like this: 它是这样的:

In a file that we will name example.js, you write: 在我们将其命名为example.js的文件中,您将编写:

example.js example.js

module.exports = "some code";

Now, you want this string "some code" in another file. 现在,您希望将此字符串“某些代码”存储在另一个文件中。

We will name the other file otherFile.js 我们将另一个文件命名为otherFile.js

In this file, you write: 在此文件中,您编写:

otherFile.js otherFile.js

let str = require('example.js')

That require() statement goes to the file that you put inside of it, finds whatever data is stored on the module.exports property. 该require()语句转到您放入其中的文件,查找存储在module.exports属性中的所有数据。 The let str = ... part of your code means that whatever that require statement returns is stored to the str variable. 代码的let str = ...部分意味着将require语句返回的任何内容存储到str变量中。

So, in this example, the end-result is that in otherFile.js you now have this: 因此,在此示例中,最终结果是在otherFile.js中,您现在有了以下代码:

let string = "some code"; let string =“某些代码”;

  • or - 要么 -

let str = ('./example.js').module.exports 让str =('./example.js').module.exports

Note: 注意:

the file-name that is written inside of the require statement: If it is a local file, it should be the file-path to example.js. 在require语句中写入的文件名:如果是本地文件,则应为example.js的文件路径。 Also, the .js extension is added by default, so I didn't have to write it. 另外,.js扩展名是默认添加的,因此我不必编写它。

You do something similar when requiring node.js libraries, such as Express. 当需要诸如Express的node.js库时,您可以执行类似的操作。 In the express.js file, there is an object named 'module', with a property named 'exports'. 在express.js文件中,有一个名为“模块”的对象,其对象名为“ exports”。

So, it looks something like along these lines, under the hood (I am somewhat of a beginner so some of these details might not be exact, but it's to show the concept: 因此,它看起来像是沿着这些思路,在幕后(我是个初学者,所以其中一些细节可能并不准确,但这只是为了展示这个概念:

express.js express.js

module.exports = function() {//It returns an object with all of the server methodsreturn {listen: function(port){},get: function(route, function(req, res){}){}}
}

If you are requiring a module, it looks like this: const moduleName = require("module-name"); 如果需要模块,则如下所示:const moduleName = require(“ module-name”);

If you are requiring a local file, it looks like this: const localFile = require("./local-file"); 如果需要本地文件,则如下所示:const localFile = require(“ ./ local-file”);

(notice the ./ at the beginning of the file name) (注意文件名开头的./)


Also note that by default, the export is an object .. eg module.exports = {} So, you can write module.exports.myfunction = () => {} before assigning a value to the module.exports. 另请注意,默认情况下,导出是一个对象。例如,module.exports = {}因此,您可以在为module.exports赋值之前编写module.exports.myfunction =()=> {}。 But you can also replace the object by writing module.exports = "I am not an object anymore." 但是您也可以通过编写module.exports =“我不再是对象了”来替换该对象。


#4楼

Two flavours of module.exports / require: 两种形式的module.exports /要求:

(see here ) (请参阅此处 )

Flavour 1 口味1
export file (misc.js): 导出文件(misc.js):

var x = 5;
var addX = function(value) {return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

other file: 其他档案:

var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));

Flavour 2 口味2
export file (user.js): 导出文件(user.js):

var User = function(name, email) {this.name = name;this.email = email;
};
module.exports = User;

other file: 其他档案:

var user = require('./user');
var u = new user();

#5楼

So what is this "require?" 那么这是什么“要求”?

require() is not part of the standard JavaScript API. require()不是标准JavaScript API的一部分。 But in Node.js, it's a built-in function with a special purpose: to load modules . 但是在Node.js中,它是一个内置函数,具有特殊目的: 加载模块 。

Modules are a way to split an application into separate files instead of having all of your application in one file. 模块是一种将应用程序拆分为单独文件的方法,而不是将所有应用程序都包含在一个文件中。 This concept is also present in other languages with minor differences in syntax and behavior, like C's include , Python's import , and so on. 其他语言在语法和行为上也存在细微差别,例如C的include ,Python的import等等。

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code. Node.js模块和浏览器JavaScript之间的一大区别是如何从另一个脚本的代码访问一个脚本的代码。

  • In browser JavaScript, scripts are added via the <script> element. 在浏览器JavaScript中,脚本是通过<script>元素添加的。 When they execute, they all have direct access to the global scope, a "shared space" among all scripts. 当它们执行时,它们都可以直接访问全局范围,即所有脚本之间的“共享空间”。 Any script can freely define/modify/remove/call anything on the global scope. 任何脚本都可以在全局范围内自由定义/修改/删除/调用任何内容。

  • In Node.js, each module has its own scope. 在Node.js中,每个模块都有自己的作用域。 A module cannot directly access things defined in another module unless it chooses to expose them. 一个模块不能直接访问另一个模块中定义的内容,除非它选择公开它们。 To expose things from a module, they must be assigned to exports or module.exports . 从模块揭露的事情,他们必须被分配到exportsmodule.exports For a module to access another module's exports or module.exports , it must use require() . 为了使一个模块访问另一个模块的exportsmodule.exports必须使用require()

In your code, var pg = require('pg'); 在您的代码中, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. 加载pg模块,这是Node.js的PostgreSQL客户端。 This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable. 这使您的代码可以通过pg变量访问PostgreSQL客户端API的功能。

Why does it work in node but not in a webpage? 为什么它在节点中有效但在网页中无效?

require() , module.exports and exports are APIs of a module system that is specific to Node.js. require() module.exportsexports是一个模块系统特定于Node.js的的API的 Browsers do not implement this module system. 浏览器未实现此模块系统。

Also, before I got it to work in node, I had to do npm install pg . 另外,在我让它在节点上工作之前,我必须做npm install pg What's that about? 那是什么意思

NPM is a package repository service that hosts published JavaScript modules. NPM是一个软件包存储库服务,用于承载已发布的JavaScript模块。 npm install is a command that lets you download packages from their repository. npm install是一个命令,可让您从其存储库下载软件包。

Where did it put it, and how does Javascript find it? 它放在哪里,以及Javascript如何找到它?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install . npm cli将所有下载的模块放在运行npm installnode_modules目录中。 Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory. Node.js拥有关于模块如何查找其他模块的非常详细的文档,其中包括查找node_modules目录。


#6楼

It's used to load modules. 它用于加载模块。 Let's use a simple example. 让我们用一个简单的例子。

In file circle_object.js : 在文件circle_object.js

var Circle = function (radius) {this.radius = radius
}
Circle.PI = 3.14Circle.prototype = {area: function () {return Circle.PI * this.radius * this.radius;}
}

We can use this via require , like: 我们可以通过require来使用它,例如:

node> require('circle_object')
{}
node> Circle
{ [Function] PI: 3.14 }
node> var c = new Circle(3)
{ radius: 3 }
node> c.area()

The require() method is used to load and cache JavaScript modules. require()方法用于加载和缓存JavaScript模块。 So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require() method. 因此,如果要将本地的相对JavaScript模块加载到Node.js应用程序中,则只需使用require()方法。

Example: 例:

var yourModule = require( "your_module_name" ); //.js file extension is optional

这个Javascript“要求”是什么?相关推荐

  1. 【AJAX】JavaScript的面向对象

    Ajax中后端数据返回后需要前端通过JavaScript来实现动态数据更新的问题.所以,在Ajax中加深了一遍JavaScript面向对象的印象. 基础部分: JavaScript中创建对象并简单对象 ...

  2. 【JavaScript总结】JavaScript语法基础:JS高级语法

    作用域链: 1.JS中只有函数能够限定作用域的范围: 2.变量处理在制定的函数范围内,还有一个特殊的作用域,就是没有用var 声明的全局作用域 3.js中的作用域链是为了清晰的表示出所有变量的作用范围 ...

  3. 【JavaScript总结】JavaScript语法基础:DOM

    ->DOM的理解:文档对应dom树 ->有了DOM能做什么:DOM的操作 html文档做为DOM树模型,DOM树的节点就是对象.对象会触发事件来执行一些事件代码. C#中的事件是一个委托变 ...

  4. 【JavaScript总结】JavaScript语法基础:JS编码

    运算符 数学:+. -. *. / 逻辑:>. < .>= .<=. == . !=.&&.|| . === .!==(完全等于) 对象相关 new delet ...

  5. 【JavaScript总结】JavaScript语法基础:数据类型

    ------>数据类型有哪些? ->基本类型:数字类型,布尔类型,字符串类型 ->引用类型:对象类型,函数类型 ->空类型:null 和 undefined ->运算符: ...

  6. 【JavaScript总结】JavaScript发展与学习内容

    发展: 最初浏览器是为大学里浏览文档用,从地址栏输入文档地址,找到文档显示. 后来各种需求(购物网站,个人博客)出现,已有功能不能满足需求. 可人们依旧在努力满足这种需求,但实现后的效果很不尽人意. ...

  7. Python:模拟登录、点击和执行 JavaScript 语句案例

    案例一:网站模拟登录 # douban.pyfrom selenium import webdriver from selenium.webdriver.common.keys import Keys ...

  8. [JavaScript] JavaScript数组挖掘,不只是讲数组哟(2)

    课程来源:后盾人 上一篇的内容:[JavaScript] JavaScript数组挖掘,不只是讲数组哟 数组引用类型分析,多维数组,用Array.of为数组创建细节,类型检测与转换,在一个数组后面加一 ...

  9. [JavaScript] JavaScript 数组挖掘,不只是讲数组哟

    课程来源:后盾人 数组引用类型分析 数组的定义 const array = new Array('hello', 'dust', 1, 2, 3, 4, 5) console.log(array) l ...

  10. linux下用js生成xml,js2xml:将javascript字符串转换为xml

    有时候爬数据遇到像下面这种,数据在script标签中以javascript形式存在. var totalReviewsValue = 32; var averageRating = 4.5; if(t ...

最新文章

  1. rust设置里面那个是能见度_IDEA maven设置里面的Repositories这个设置问题
  2. 【实战】感恩教师节小程序制作
  3. 你不知道的vscode之空间控制
  4. 可自由扩展的圆角矩形制作方法
  5. antd autoplay按f12才会轮播_涨知识了!原来这才是电脑键盘上,F1到F12的正确用法...
  6. (转)详解JS位置、宽高属性之一:offset系列
  7. Openssl verify命令
  8. JDK18 Java 18 拥有 9 个新特性
  9. WebGIS开发之用openlayers加载离线百度地图
  10. 完全二叉树/ 满二叉树/二叉树遍历(前序、中序、后序、层序遍历)
  11. 五个金念什么_5个火读什么???还有5个水 5个木 5个土 5个金
  12. python-读取dcm文件-2021.5.24
  13. 硬盘sata供电不启动,必须用大4pin转sata的情况
  14. 接口--PCI/PCIE
  15. OI中常见的数学符号
  16. java转盘_Java 实现大转盘抽奖
  17. 手机与电脑共享文件资源的几种方法
  18. 【数据挖掘实验】利用朴素贝叶斯方法对百万搜狐新闻文本数据进行分类
  19. ubantu启动黑屏解决办法
  20. 利用蒲公英自动更新APP及其更新机制

热门文章

  1. int 和String之间的互转
  2. 使用quirksmode来简化开发
  3. JS——构造函数、原型与实例之间的关系 及 原型链 的描述
  4. leveldb 安装及使用
  5. [CODEVS1911] 孤岛营救问题(分层图最短路)
  6. PHP error_reporting() 错误控制函数功能详解
  7. urlencode编码问题(以及urlparse)
  8. Qt 5 如何修改打包好的应用程序图标
  9. 李开复:一切靠命运或靠自己都是不合适的
  10. Zabbix email 配置