- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想创建一个node.js应用程序,对一些站点进行web抓取,将数据保存在postgresql数据库中,然后在网页上显示这些数据的可视化(在d3.js中)。
我考虑了拆分前端部分(创建和显示可视化)和后端部分(进行web抓取和更新db)。
这两个应用程序的框架(有两个是因为我将任务分为两个应用程序)如下所示。
后端应用程序(scraper
):
连接到数据库
如果表不存在,则创建它们
数据刮刀
在数据库中保存数据
断开与数据库的连接。
这个后端应用程序一年只能启动几次(为此,如果使用的是unix,我可以配置cron文件)。
前端应用程序(viz
):
连接到数据库
启动等待端口3000的服务器(我需要它进行可视化)
每次用户刷新页面(onLoad()
)时,应用程序都会进行查询(SELECT
),从数据库中获取数据。这样,数据总是更新的。
这个应用程序只由程序员启动一次(理想情况下)。
我创建了这种类型的文件夹结构(我使用了npm init
和Express
):
project
|_ scraper
|_ helpers // contains some useful .js files
|_ elaborateJson.js
|_ saveOnDb.js
|_ utilFunc.js
|_ node_modules // modules installed using `npm install moduleName --save`
|_ routes // contains the files that make scraping
|_ downloaderHome.js
|_ downloaderWork.js
|_ services // contains a files concerning the db
|_ postgreSQLlib.js
|_ app.js
|_ package.json
|_ package-lock.json
|_ viz
|_ helpers // // contains some useful .js files
|_ utilFunc.js
|_ node_modules // modules installed using `npm install moduleName --save`
|_ public // contains files for visualizations
|_ index.handlebars
|_ script.js
|_ style.css
|_ services // contains a file concerning the db
|_ postgreSQLlib.js
|_ app.js
|_ package.json
|_ package-lock.json
postgreSQLlib.js
文件(以及
utilFunc.js
)在
scraper
和
viz
中都是相同的。如何避免代码重复?
express-handlebars
和
express
文件夹中安装一些模块(例如
scraper
和
viz
)两次。
project/scraper/app.js
:
const downloaderHome = require('./routes/downloaderHome.js');
const downloaderWork = require('./routes/downloaderWork.js');
const postgreSQLlib = require('./services/postgreSQLlib.js');
const saveOnDb = require('./helpers/saveOnDb.js');
const utilFunc = require('./helpers/utilFunc.js');
const express = require('express');
const exphbs = require('express-handlebars');
var app = express();
start();
async function start() {
console.log('\n Connect to db');
await postgreSQLlib.connect();
console.log('\n Create tables if they do not exist');
await postgreSQLlib.createHomeTable();
await postgreSQLlib.createWorkTable();
console.log('\n Check if table \'home\' is updated or not');
if(!await utilFunc.isTableUpdated('home', 6418)) { // 6308
console.log('\n Download data for home');
await downloaderHome.download();
console.log('\n Saving data for home on db');
await saveOnDb.saveHome();
}
console.log('\n Check if table \'work\' is updated or not');
if(!await utilFunc.isTableUpdated('work', 6804)) {
console.log('\n Download data for work');
await downloaderWork.download();
console.log('\n Saving data for work on db');
await saveOnDb.saveWork();
}
console.log('\n Disconnect from db');
await postgreSQLlib.disconnect();
}
project/viz/app.js
:
const postgreSQLlib = require('./services/postgreSQLlib.js');
const utilFunc = require('./helpers/utilFunc.js');
const express = require('express');
const exphbs = require('express-handlebars');
const http = require('http');
var app = express();
var response;
var callback;
start();
async function start() {
console.log('\n Connect to db');
await postgreSQLlib.connect();
// how do I check when page is refreshed?!
http.get({
hostname: 'localhost',
port: 3000,
path: '/',
agent: false
}, callback);
callback = function(res) {
response = res;
console.log(response); // here response will return an object
console.log('refresh callback');
}
console.log(response);
console.log('refresh');
///////////////////////////////////////////////
// How do I check the disconnection from the db?
// If I disconnect now, the visualizations are no longer work.
// So when do I get disconnected?
// Create problems leaving the connection to the active db?
///////////////////////////////////////////////
//console.log('\n Disconnect from db');
//await postgreSQLlib.disconnect();
}
project/scraper/app.js
)工作得很好。
project/viz/app.js
)没有。我希望您这样做:
onLoad()
)时,应用程序都会进行查询(
SELECT
),从数据库中获取数据[我该怎么做?]
async function start() {
console.log('\n Connect to db');
await postgreSQLlib.connect();
console.log('\n Get data from db');
var dataHome = await postgreSQLlib.getTableHome();
var dataWork = await postgreSQLlib.getTableWork();
//console.log('\n Connect to my server');
pageLoad(dataHome, dataWork);
}
function pageLoad(dataHome, dataWork) {
var hbs = exphbs.create({
helpers: {
getDataHome: function() {
return JSON.stringify(dataHome);
},
getDataWork: function() {
return JSON.stringify(dataWork);
}
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.get('/', function(req, res, next) {
res.render('index', { // index is html filename
showTitle: true,
});
});
console.log('Go to http://localhost:3000/ to see visualizations');
app.listen(3000);
}
dataHome
和
dataWork
是两个对象,它们包含使用
SELECT
查询从数据库下载的数据。
const postgreSQLlib = require('../shared_libs/postgreSQLlib.js');
const express = require('express');
var app = express();
start();
async function start() {
console.log('Connect to db');
await postgreSQLlib.connect();
app.get('/', fetchFreshData);
}
async function fetchFreshData(req, res) {
// download data from db
var dataHome = await postgreSQLlib.getTableHome();
var dataWork = await postgreSQLlib.getTableWork();
// fill this JSON using the results
var viewData = {dataHome, dataWork};
// pass data to view
res.render('index', viewData);
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Map</title>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<link rel='stylesheet' type='text/css' href='/style.css' media='screen'/>
</head>
<body>
<div id='example'></div>
</body>
<script src='/script.js'></script>
</html>
console.log('viewData:', viewData);
viz/app.js
代码:
const postgreSQLlib = require('../shared_libs/postgreSQLlib.js');
const express = require('express');
const exphbs = require('express-handlebars');
var app = express();
start();
async function start() {
await postgreSQLlib.connect();
var hbs = Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.get('/', fetchFreshData);
console.log('Go to http://localhost:3000/ to see data');
app.listen(3000);
}
async function fetchFreshData(req, res) {
// download data from db
var dataHome = await postgreSQLlib.getTableHome();
var dataWork = await postgreSQLlib.getTableWork();
// fill this JSON using the results
var viewData = {};
viewData.timestamp = Date.now();
viewData.entries = dataHome;
// pass data to view
res.render('index', viewData);
}
returnOBJ()
而不是
res.render('index', viewData);
中,它应该是
res.render('obj', viewData);
(与
obj.hbs
文件相关)。对吗?
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Index</title>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<link rel='stylesheet' type='text/css' href='/style.css' media='screen'/>
</head>
<body>
<h1>INDEX<small>{{timestamp}}</small></h1>
</body>
<script>
// add global variables in the .hbs file
window.viewData_dataWork = {{ json entries }}
console.log(window.viewData);
</script>
<script src='/script.js'></script>
</html>
(node:207156) UnhandledPromiseRejectionWarning: Error: callback function required
at Function.engine (C:\...\node_modules\express\lib\application.js:295:11)
at start (C:\...\viz\app.js:20:6)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:182:7)
(node:207156) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:207156) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express);
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('view engine', ...)
两次?
const postgreSQLlib = require(__dirname + './../shared_libs/services/postgreSQLlib.js');
const express = require('express');
const hbs = require('hbs');
var app = express();
// Server initiator
async function start() {
await postgreSQLlib.connect();
// hbs
app.set('views', '' + __dirname + '/views');
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express);
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// router
app.get('/', testMe);
console.log('Go to http://localhost:3000/ to see data');
app.listen(3000);
}
// Your section with fresh data has been populated properly
async function testMe(req, res) {
console.log('testMe');
// fill this JSON using the results
var viewData = {};
viewData.data = 'this string';
// pass data to view
res.render('test', viewData);
}
// start the server
start();
<html>
<head>
<title>Server test</title>
</head>
<body>
{{data}}
</body>
</html>
project/viz
并键入
node app.js
+enter。
http://localhost:3000/
但连接失败时。
connect
或者选择的函数,所以我稍微简化了代码。
const postgreSQLlib = require(__dirname + './../shared_libs/services/postgreSQLlib.js');
const express = require('express');
var app = express()
const hbs = require('hbs');
const webapp_opts = {"port":3000};
Initialize();
//.: Setup & Start Server
async function Initialize(){
await postgreSQLlib.connect();
console.log("[~] starting ...")
//:[HBS]:Setup
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express)
app.set('views', "" + __dirname + "/views")
//:[HBS]:Helpers
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
})
//:[EXPRESS]:Router.Paths
app.get("/", IndexPathFunction);
// app.get("/script.js", scriptFile); <-- for script.js file
//:[EXPRESS]:Start
app.listen(webapp_opts.port,()=>{
console.log("[i] ready & listening","\n http://localhost:"+webapp_opts.port+"/")
})
}
/*async function scriptFile(req, res) { <-- for script.js file
console.log('\nscriptFile');
var viewData = {};
viewData.number = 50;
console.log('viewData:', viewData);
res.render('script.js', viewData);
}*/
//.: Router Function : "/"
async function IndexPathFunction(req,res){
var viewData = {};
viewData.timestamp = Date.now();
viewData.exJson = [{color: 'red', year: '1955'}, {color: 'blue', year: '2000'}, {color: 'yellow', year: '2013'}];
viewData.exString = 'example of string';
console.log('viewData:', viewData);
res.render('index', viewData);
}
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Index</title>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<link rel='stylesheet' type='text/css' href='/style.css' media='screen'/>
</head>
<body>
<h1>INDEX timestamp: <small>{{timestamp}}</small></h1>
</body>
<script>
viewData = {};
console.log('viewData:', viewData);
viewData.exJson = JSON.parse('{{ json exJson }}'.replace(/"/g, '"').replace(/</, ''));
viewData.timestamp = {{timestamp}}; // doesn't work
viewData.exString = {{ exString }}; // doesn't work
console.log('viewData.exJson:', viewData.exJson);
console.log('viewData.timestamp:', viewData.timestamp);
console.log('viewData.exString:', viewData.exString);
</script>
<!--<script src='/script.js'></script>-->
</html>
script.js
文件中,该文件由
index.hbs
使用
<script src='/script.js'></script>
调用。
index.hbs
,但其思想是将
console.log('here');
变量放入script.js中)来编辑
viewData
文件。
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Index</title>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<link href="/css/style.css" rel="stylesheet">
</head>
<body>
<img src="/images/logo.png"/>
<h1>timestamp: <small>{{timestamp}}</small></h1>
<h2>Welcome in index.hbs</h2>
</body>
<script>
viewData = {};
console.log('viewData:', viewData);
viewData.exJson = JSON.parse('{{json exJson }}'.replace(/"/g, '"').replace(/</, ''));
viewData.timestamp = {{timestamp}};
viewData.exString = '{{exString}}';
console.log('viewData.exJson:', viewData.exJson);
console.log('viewData.timestamp:', viewData.timestamp);
console.log('viewData.exString:', viewData.exString);
</script>
<link href='/script/script.js' rel='script'>
</html>
project
|_ node_modules
|_ scraper
|_ shared_libs
|_ viz
|_ app.js
|_ public
|_ css
|_ style.css
|_ images
|_ logo.png
|_ script
|_ script.js
|_ views
|_ index.hbs
最佳答案
共享(自定义)代码的解决方案:
有了这个结构,我已经有两个问题,我不知道怎么解决
要解决:
scraper和viz中的postgreSQLlib.js
文件(以及utilFunc.js
)都是相同的。如何避免代码重复?
您已经在使用require
,因此请从以下位置移动文件:
project/scraper/services/postgreSQLlib.js
project/viz/services/postgreSQLlib.js
project
|_ shared_libs
|_ scraper
|_ viz
shared_libs
,您可以随意命名)
project/shared_libs/postgreSQLlib.js
const postgreSQLlib = require(__dirname+"/../shared_libs/postgreSQLlib.js");
node_modules
project/scraper/node_modules
project/viz/node_modules
project
目录根目录中的文件夹
project/node_modules
project/scraper
&
project/viz
)
npm i <module> --save
目录中的
project
。
project/scraper
和
project/viz
都将使用
project/node_modules
project/viz/app.js
的解决方案
GET
请求上从db获取数据
app.get('/',FetchFreshData)
function FetchFreshData(req,res){
/* add your SELECT here */
var viewData = {} //fill this JSON using the results
res.render('index',viewData)
}
GET
到“/”路由时,您都将运行查询并接收带有新数据的“可视化”。
Handlebars.registerHelper('json',function(context){
return JSON.stringify(context)
})
function FetchFreshData(req,res){
/* add your SELECT here */
var viewData = {} //fill this JSON using the results
viewData.timestamp = Date.now()
viewData.entries = dataHome
res.render('index',viewData)
}
{
"timestamp":"1525182734",
"entries":[
{"name":"Entry 1"},
{"name":"Entry 2"},
{"name":"Entry 3"}
]
}
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Map</title>
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<link rel='stylesheet' type='text/css' href='/style.css' media='screen'/>
</head><body>
<h1>MAP<small>{{timestamp}}</small></h1>
<div id='example'>
{{#if entries}}
<ul>
{{#each entries}}
<li> this.name </li>
{{/each}}
</ul>
{{else}} No content... {{/if}}
</div>
</body>
<script>
//Add global variables in the .hbs file
window.viewData_entries = {{ json entries }}
</script>
<script src='/script.js'></script>
</html>
hbs
并尝试使用我的两个返回时间戳和对象的简单示例,我还在某些部分修复了您的代码,以便您继续改进它以满足您的更多需求。
const postgreSQLlib = require('../shared_libs/postgreSQLlib.js');
const express = require('express');
const hbs = require('hbs')
var app = express();
//:Server Initiator
async function start() {
await postgreSQLlib.connect();
//:HBS:
app.set('views', "" + __dirname + "/views");
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express);
hbs.registerHelper('json',function(context){return JSON.stringify(context)});
//:Router:
app.get('/', fetchFreshData);
app.get('/timestamp', returnTimestamp);
app.get('/obj', returnOBJ);
console.log('Go to http://localhost:3000/ to see data');
app.listen(3000);
}
//:Your section with fresh data has been populated properly
async function fetchFreshData(req, res) {
var viewData = {};
viewData.timestamp = Date.now();
viewData.dataWork = await postgreSQLlib.getTableWork();
viewData.dataHome = await postgreSQLlib.getTableHome();
// pass data to view
res.render('index', viewData);
}
/*
The index.hbs I posted earlier wont work anymore, since the "entries" key doesnt exist now... Try to understand the template engine with the following 2 examples below
*/
//:Simple Timestamp EXAMPLE
function returnTimestamp(req, res) {
var viewData = {};
viewData.timestamp = Date.now();
// pass data to view
res.render('timestamp_example', viewData);
}
/* This would be timestamp_example.hbs :
<html><head><title>Server Timestamp</title></head><body>{{timestamp}}</body></html>
*/
//:Simple JSON EXAMPLE
function returnOBJ(req, res) {
var viewData = {};
viewData.OBJ = {"key":"value"};
// pass data to view
res.render('json_example', viewData);
}
/* This would be json_example.hbs :
<html><head><title>Server Object</title></head><body>Page will alert "{{OBJ.key}}"<script>var OBJ = {{json OBJ}}; alert(OBJ.key);</script></body></html>
*/
//start the server :
start()
/timestamp
和
/obj
路径添加新视图,我在每个服务器函数下面都添加了一个注释示例。
----------
const express = require('express'); var app = express()
const hbs = require('hbs')
const webapp_opts = {"port":3000}
//.: Setup & Start Server
function Initialize(){
console.log("[~] starting ...")
//:[HBS]:Setup
app.set('view engine', 'hbs'); app.engine('hbs', hbs.__express)
app.set('views', "" + __dirname + "/views")
//:[HBS]:Helpers
hbs.registerHelper('json',function(context){return JSON.stringify(context)})
//:[EXPRESS]:Router.Paths
app.get("/",IndexPathFunction)
app.get("/debug",(req,res)=>{
console.log("[GET]:/debug"); res.send("ok")
})
//:[EXPRESS]:Start
app.listen(webapp_opts.port,()=>{
console.log("[i] ready & listening","\n http://localhost:"+webapp_opts.port+"/")
})
}
//.: Router Function : "/"
function IndexPathFunction(req,res){
DBQuery((query_error,query_results)=>{
if(query_error){console.log("[!] DBQuery @ path : '/'\n",query_error.stack)}
else{
console.log("[+] DBResults :",query_results)
res.render("index",{data:query_results})
/*or*/// var viewData = {}; viewData.data=query_results; res.render("index",viewData)
}
})
}
//:[DB]:Example Query using callback method
function DBQuery(callback_function){
console.log("[>] DBQuery")
pool.connect((err,client)=>{
if (err) throw err
client.query('SELECT * FROM whatever',(err,res)=>{
client.release()
callback_function(err,res)
})
})
}
//------------------------------------
/* We can Initialize() the webapp
once we know the DB is accesible : */
const pg = require('pg')
const db_opts = {
"user":"dbuser","password":"secretpassword",
"host":"database.server.com", "port":3211,
"database":"mydb"
})
var pool = new pg.Pool(db_opts);
pool.on('error',(err,client)=>{
console.error('Unexpected error on idle client', err); process.exit(-1)
})
pool.connect((err,client,done)=>{
if(err){console.log("[!] DB Connection Error",err)}
else{console.log("[+] DB Connected"); client.release(); Initialize() }
})
关于node.js - Node.js:表达路线,从数据库查询数据并在template.hbs View 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50079276/
template struct List { }; template class> struct ListHelper; template struct ListHelper> { };
最近,我注意到 html/template.Template 的 Templates() 与 text/template.Template 的工作方式不同。 // go1.12 func main()
我正在尝试使用 polymer 1.0 实现一个网站。我有一个自定义元素 my-greeting,里面有一些模板重复。 我想做的是获取一个名为 TARGET 的字符串,但我不知道该怎么做: /cons
(是的,由于我糟糕的英语,标题很奇怪;我希望有人能改进它。) 接听this question ,我发现这段代码有效: template class A { }; template class U>
这个问题在这里已经有了答案: How to import and use different packages of the same name (2 个答案) 关闭 4 年前。 我正在使用 Go
我的想法是这是不可能的,或者我缺少一个额外的步骤。无论哪种方式,我都被卡住了,无法弄清楚。 使用内联模板的原因是能够使用 Laravel Blade 语法并结合 Vue Js 的强大功能。似乎是两者中
我已经尝试实现一个“模板模板模板”——模板类来满足我的需求(我对使用模板元编程很陌生)。不幸的是,我发现以下主题为时已晚: Template Template Parameters 不过,我需要实现如
Helm _helpers.tpl? Helm 允许使用 Go templating在 Kubernetes 的资源文件中。 一个名为 _helpers.tpl 的文件通常用于定义 Go 模板助手,语
{{template "base"}} 和 {{template "base".}} 有什么区别? 我用的是go-gin,两者都可以正常运行。我在文档中找不到关于此的任何描述。 最佳答案 来自 god
我有一个本质上充当查找表的函数: function lookup(a::Int64, x::Float64, y::Float64) if a == 1 z = 2*x + y else if a =
当 out 成员函数(来自模板和特化)都需要模板时,为什么 c++ 需要模板参数,因为我没有得到它,谷歌也没有帮助。必须是c++11但和c++1z有同样的错误。 我正在使用 g++ 7.3.0 收到此
我正在寻找简单的方法来将带有 ${myvar} 的简单模板转换为带有 {{ myvar }} 的 GO 模板。 是否有任何库可以实现这一点? 最佳答案 使用正则表达式查找 \${([a-z0-9\_\
我有这个模板可以将 slice 的多个项目解析到页面上。它确实做得很好。 但是,我现在想使用完全相同的模板来根据范围索引解析 slice 的单个值。该 slice 在多个文件中使用,所以我不能像 Sl
要清理模板文件夹,我想将常用模板保存在子文件夹中。目前我有以下文件结构: main.go templates/index.tpl # Main template for the
最近我设计了元类型和允许编译时类型连接的可能操作: #include template typename T> struct MetaTypeTag {}; /*variable template
准备模板时发生错误。谁能告诉你怎么修? 如有必要,还可以编辑变量。 vars: AllСountry: - "name1" - "name2"
我在使用新的匿名模板引擎时遇到问题。它不能使用嵌套模板。我收到错误消息:“此模板引擎不支持嵌套在其模板中的匿名模板”。 我的问题:我如何强制 knockout JS 使用jquery 模板引擎,而不是
这个问题在这里已经有了答案: Where and why do I have to put the "template" and "typename" keywords? (8 个答案) 关闭 8
我在 C++ 中使用带有模板的集合: template class OMSSVDisk : public OMSSObjProperties{ set memberPDs; }; 如上面代码中
因为我喜欢分离接口(interface)和实现,而不是只在头文件中实现模板类,我将它分成 .h 和 .tpp(.tpp 这样它就不会用 *.cpp 编译)。然后我将 tpp 包含在头文件的末尾,就在
我是一名优秀的程序员,十分优秀!