gpt4 book ai didi

javascript - Node JS : Getting started with express

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:37 25 4
gpt4 key购买 nike

我是 NodeJS 和 Express 框架的新手。使用 Express 的原因是它是最好的 NodeJS Web 框架之一。这是我的问题:
我有一个 bitcoinTest.js,它在屏幕上打印一些结果。想要将其显示在网页上。
bitcoinTest.js

var bitcoin = require('bitcoin');
var client = new bitcoin.Client({
host: 'localhost',
port: 8332,
user: 'himanshuy',
pass: 'xxxx'
});

client.getDifficulty(function(err, difficulty) {
if(err) {
return console.error(err);
}

console.log('Difficuly: ' + difficulty);
});

client.getInfo(function(err, info) {
if(err) return console.log(err);
console.log('Info: ', info);
});

server.js

var express = require('express');
var app = express();
app.listen(3000);

app.get('/', function(req, res){
res.send('Hello World');
});

app.get('/getDifficulty', function(req, res){
res.send('Get detail from BitcoinTest file');
});

app.get('/getInfo', function(req, res){
res.send('Get detail from BitcoinTest file');
});

我将如何实现最后两条路线并从 bitcoinTest.js 获取详细信息?

最佳答案

看来您的问题不在于 Express,而在于缺乏对 Node 的了解。首先,我会阅读有关 Node 模块的内容:

http://nodejs.org/api/modules.html

您可以采用您编写的内容,简单地导出 bitcoin.Client 对象并从您的应用程序文件中使用它,但您实际上除了使用 bitcoin.Client 方法之外,没有做任何事情,那么为什么不将其全部放入您的应用程序文件中呢?所以你的应用程序文件将变成这样:

var http = require('http'),
express = require('express'),
bitcoin = require('bitcoin');

var app = express();

var client = new bitcoin.Client({
host: 'localhost',
port: 8332,
user: 'himanshuy',
pass: 'xxxx'
});

app.get('/', function(req, res){
res.send('Hello World');
});

app.get('/getDifficulty', function(req, res){
client.getDifficulty(function(err, difficulty) {
if(err) {
res.send('Bitcoin error: ' + err);
} else {
res.send('Difficulty: ' + difficulty);
}
});
}

app.get('/getInfo', function(req, res){
client.getInfo(function(err, info) {
if(err) {
res.send('Bitcoin error: ' + err);
} else {
res.send('Info: ' + info);
});
});

http.createServer(app).listen(3000, function(){
console.log('Server started on port 3000');
});

如果您开始添加更多比特币功能(不仅仅是调用 bitcoin.Client)方法,那么创建一个模块是有意义的。你可以有这样的东西:

lib/bitcoin.js

var bitcoin = require('bitcoin');

module.exports = function(options){

var client = new bitcoin.Client({
host: options.host,
port: options.port,
user: options.user,
pass: options.pass,
});

return {
myMethod1: function(){
// uses client and returns something useful
},
myMethod2: function(){
// uses client and returns something useful
}
}

然后你可以像这样使用它:

var myBitcoin = require('./lib/bitcoin.js')({
host: 'localhost',
port: 8332,
user: 'himanshuy',
pass: 'xxxx'
});

// now you can use your custom methods
myBitcoin.myMethod1(/*whatever*/);

关于javascript - Node JS : Getting started with express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21539835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com