这个Javascript“要求”是什么?

本文翻译自: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: 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." 我在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 methods
    return {
        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.14

Circle.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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值