我的Node模块中的对象没有我期望的行为 - Node.js

时间:2021-07-12 12:21:19

I am a newbie with Node and I am trying to learn how to make my modules work. Here is my express app:

我是Node的新手,我正在努力学习如何使我的模块工作。这是我的快递应用程序:

var express = require('express');
var app = express();

var client = require('./config/postgres.js');

app.get('/users', function(req, res) {
  var query = client.query('SELECT * FROM users');
  query.on('row', function(row, result) {
    result.addRow(row);
  });
  query.on('end', function(result) {
    res.json(result);
  });
});

And here is my module that I am trying to require

这是我试图要求的模块

var pg = require('pg').native;
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/isx';
var client = new pg.Client(connectionString);
client.connect();
module.exports.client = client;

but in my main app, my client has no method 'query'. If I just inline the code that is in the module and I am requireing in, then everything works fine. What is the difference between the 2 ways to access the code?

但在我的主应用程序中,我的客户端没有方法'查询'。如果我只是内联模块中的代码并且我需要,那么一切正常。访问代码的两种方法有什么区别?

2 个解决方案

#1


2  

var client = require('./config/postgres.js');

...sets client equal to the export object in your import. Since the export object has a single client property with the query function,

...将客户端设置为等于导入中的导出对象。由于导出对象具有带查询功能的单个客户端属性,

client.client.query()

is what you're looking for.

是你在找什么。

If you want to export just the client, use;

如果您只想导出客户端,请使用;

module.exports = client;

#2


1  

Your are exporting this:

你出口这个:

{
    "client": [Function]
 }

Just access the key that stores the function when you require the module or export only the function and nothing more:

只需在需要模块时访问存储函数的键或仅导出函数,仅此而已:

module.exports = client;

#1


2  

var client = require('./config/postgres.js');

...sets client equal to the export object in your import. Since the export object has a single client property with the query function,

...将客户端设置为等于导入中的导出对象。由于导出对象具有带查询功能的单个客户端属性,

client.client.query()

is what you're looking for.

是你在找什么。

If you want to export just the client, use;

如果您只想导出客户端,请使用;

module.exports = client;

#2


1  

Your are exporting this:

你出口这个:

{
    "client": [Function]
 }

Just access the key that stores the function when you require the module or export only the function and nothing more:

只需在需要模块时访问存储函数的键或仅导出函数,仅此而已:

module.exports = client;