我知道全局变量不好。
但是,如果我在框架中的40个文件中使用节点的模块“ util”,那么最好仅将其声明为全局变量,例如:
util = require('util');
在index.js文件中,而不是在40个文件中写入该行?
因为我经常在每个文件中使用相同的5-10个模块,这样可以节省大量时间,而不是一直复制粘贴。
在这种情况下DRY不好吗?
如何从电子应用程序中删除此菜单栏:
它还说“ Hello World”(这是因为我下载了预先构建的电子,并且打包应用程序后就会消失吗?)。 我没有将这些代码编码到html中,所以我不知道如何将其发布!
我试图用优胜美地在Mac上安装grunt。 节点已经安装了最新版本。 如果我在终端中输入“ node -v”,我会得到v0.12.5行。 那很好。 但是当我想用npm安装某些东西时,我只会得到一个错误...
我尝试了“ sudo npm install -g grunt-cli”,“ sudo npm install npm -g”以及“ npm -v”,我总是收到此错误...
Error: Cannot find module 'are-we-there-yet'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/usr/local/Cellar/node/0.10.22/lib/node_modules/npm/node_modules/npmlog/log.js:2:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
有人知道这是什么问题还是更好的解决方案?
我正在使用Express.js开发其余的API,我想知道是否有一种方法可以生成允许用户查看API定义甚至可以尝试API调用的API文档?
尝试将文件上传到我的S3存储桶时遇到问题。 一切正常,除了我的文件参数似乎不合适。 我正在使用Amazon S3 sdk从nodejs上传到s3。
这些是我的路线设置:
var multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty();
app.route('/api/items/upload').post(multipartyMiddleware, items.upload);
这是items.upload()函数:
exports.upload = function(req, res) {
var file = req.files.file;
var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
s3bucket.createBucket(function() {
var params = {
Key: file.name,
Body: file
};
s3bucket.upload(params, function(err, data) {
console.log("PRINT FILE:", file);
if (err) {
console.log('ERROR MSG: ', err);
} else {
console.log('Successfully uploaded data');
}
});
});
};
将Body
参数设置为类似于"hello"
的字符串可以正常工作。 根据文档,Body
参数必须获取(缓冲区,类型数组,Blob,字符串,ReadableStream)对象数据。 但是,上传文件对象失败,并显示以下错误消息:
[Error: Unsupported body payload object]
这是文件对象:
{ fieldName: 'file',
originalFilename: 'second_fnp.png',
path: '/var/folders/ps/l8lvygws0w93trqz7yj1t5sr0000gn/T/26374-7ttwvc.png',
headers:
{ 'content-disposition': 'form-data; name="file"; filename="second_fnp.png"',
'content-type': 'image/png' },
ws:
{ _writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: true,
ending: true,
ended: true,
finished: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
domain: null,
_events: { error: [Object], close: [Object] },
_maxListeners: 10,
path: '/var/folders/ps/l8lvygws0w93trqz7yj1t5sr0000gn/T/26374-7ttwvc.png',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 261937,
closed: true },
size: 261937,
name: 'second_fnp.png',
type: 'image/png' }
任何帮助将不胜感激!
我对为什么节点v6.7无法运行此代码有疑问:
var a = {
foo: 'bar'
}
var b = {
...a,
my: 'sharona'
}
console.log(b)
有人知道为什么会这样吗? 我以为v6支持对象传播。 但是我想不是吗? 这是我看到的错误:
/home/teselagen/ve/tnrtest.js:6
...a,
^^^
SyntaxError: Unexpected token ...
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:528:28)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
我们只有少数应该能够传递消息的node.js进程,最有效的方法是什么?如何使用node_redis发布/订阅
编辑:进程可能在不同的机器上运行
我使用Node.js + passport设置了一个用于用户身份验证的站点。
现在,我需要迁移到Golang,并且需要使用db中保存的用户密码进行身份验证。
Node.js加密代码为:
var bcrypt = require('bcrypt');
bcrypt.genSalt(10, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
如何使用Golang制作与Node.js bcrypt相同的哈希字符串?
注意:我在帖子末尾的自动回答
我正在尝试更好地体验nodeJS,但我真的不喜欢将所有脚本都放在一个文件中。
所以,在这里发表文章之后,我使用这种结构
./
config/
enviroment.js
routes.js
public/
css/
styles.css
images
views
index
index.jade
section
index.jade
layout.jade
app.js
我的文件现在是:
app.js
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
require('./config/routes.js')(app);
app.listen(3000);
environment.js
module.exports = function(app, express) {
app.configure(function() {
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade'); //extension of views
});
//development configuration
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
//production configuration
app.configure('production', function() {
app.use(express.errorHandler());
});
};
routes.js
module.exports = function(app) {
app.get(['/','/index', '/inicio'], function(req, res) {
res.render('index/index');
});
app.get('/test', function(req, res) {
//res.render('index/index');
});
};
layout.jade
!!! 5
html
head
link(rel='stylesheet', href='/css/style.css')
title Express + Jade
body
#main
h1 Content goes here
#container!= body
index / index.jade
h1 algoa
我得到的错误是:
错误:无法查找视图“索引/索引” 在Function.render(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ application.js:495:17) 在渲染时(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ response.js:614:9) 在ServerResponse.render(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ response.js:638:5) 在c:\ xampp \ htdocs \ nodejs \ buses \ config \ routes.js:4:7 在回调(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ router \ index.js:177:11) 在参数上(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ router \ index.js:151:11) 通过时(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ router \ index.js:158:5) 在Router._dispatch(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ router \ index.js:185:4) 在Object.router [作为句柄](c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ lib \ router \ index.js:45:10) 在下一个(c:\ xampp \ htdocs \ nodejs \ buses \ node_modules \ express \ node_modules \ connect \ lib \ proto.js:191:15)
但是我真的不知道是什么问题...
我开始思考是因为模块导出了...
回答:我发现的唯一解决方案是更改我定义的app.set('views')和views引擎的位置
我将其移至app.js,现在运行良好。
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
require('./config/routes.js')(app);
app.listen(3000);
我真的不明白这背后的逻辑,但我认为它有一个。
我花了相当长的时间在互联网上寻找可使用jsdoc正确记录回调的最佳方法,但是不幸的是,我还没有找到一个好的方法。
这是我的问题:
我正在为开发人员编写Node.js库。 该库提供了开发人员将要使用的多个类,函数和方法。
为了使我的代码清晰易懂,以及将来(希望)自动生成一些API文档,我开始在代码中使用jsdoc自行记录正在发生的事情。
假设我定义了如下函数:
function addStuff(x, y, callback) {
callback(x+y);
});
目前,使用jsdoc,我正在将此功能记录如下:
/**
* Add two numbers together, then pass the results to a callback function.
*
* @function addStuff
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {function} callback - A callback to run whose signature is (sum), where
* sum is an integer.
*/
function addStuff(x, y, callback) {
callback(x+y);
});
我觉得上面的解决方案有点像黑客一样,因为我无法绝对地指定回调函数应该接受什么。
理想情况下,我想执行以下操作:
/**
* Add two numbers together, then pass the results to a callback function.
*
* @function addStuff
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {callback} callback - A callback to run.
* @param {int} callback.sum - An integer.
*/
function addStuff(x, y, callback) {
callback(x+y);
});
上面的内容似乎使我可以更简单地传达我的回调需要接受的内容。 那有意义吗?
我想我的问题很简单:用jsdoc清楚地记录回调函数的最佳方法是什么?
感谢您的时间。
我可以找到的用于渲染带有猫鼬结果的页面的所有内容都表示要这样做:
users.find({}, function(err, docs){
res.render('profile/profile', {
users: docs
});
});
我如何从查询中返回结果,更像这样?
var a_users = users.find({}); //non-working example
这样我就可以在页面上发布多个结果?
喜欢:
/* non working example */
var a_users = users.find({});
var a_articles = articles.find({});
res.render('profile/profile', {
users: a_users
, articles: a_articles
});
能做到吗?
我正在使用Socket.IO在面向Websocket的node.js服务器上工作。 我注意到一个错误,其中某些浏览器未遵循与服务器的正确连接过程,并且未编写代码来妥善处理该错误,总之,它调用了一个从未设置的对象的方法,从而杀死了该对象 服务器由于错误。
我特别关注的不是错误,而是当发生此类错误时,整个服务器都将关闭。 我可以在节点的全局级别上做任何事情来做到这一点,因此,如果发生错误,它将仅记录一条消息,也许会杀死该事件,但是服务器进程将继续运行?
我不希望其他用户的连接断开,因为一个聪明的用户在包含的大型代码库中利用了未捕获的错误。
查看exports
的express
框架的随机源文件,有两行我不理解的代码(这些代码行几乎是所有NodeJS文件的代表)。
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
和
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
我知道第一段代码允许文件中的其余功能公开给NodeJS应用程序,但是我不清楚它的工作原理或该行代码的含义。
exports
和module.exports
实际是什么意思?
我相信第二段代码允许文件中的函数访问exports
,但同样,它是如何做到这一点的。
这些魔术词基本上是什么:exports
和exports
?
我知道npm是程序包管理器,而nvm是节点版本管理器。 我目前正在尝试使用Bash自动安装开发和生产环境,却忘记了如何开始以及以什么顺序进行。 安装npm后,我发现未安装我们的nvm。
我仍然需要安装nvm吗? 如果是这样,有什么好处?
使用shelljs创建一个子进程
!/usr/bin/env node
require('/usr/local/lib/node_modules/shelljs/global');
fs = require("fs");
var child=exec("sudo mongod &",{async:true,silent:true});
function on_exit(){
console.log('Process Exit');
child.kill("SIGINT");
process.exit(0)
}
process.on('SIGINT',on_exit);
process.on('exit',on_exit);
子进程杀死父进程后仍在运行..
目前,我们正在为客户开发一个网站(Apache下为TYPO3),该网站由node.js / socket.io应用程序支持,该应用程序可实时更新CMS提供的内容。
由于这是我们的第一个node.js项目,因此在“完美设置”方面没有任何最佳实践,因此我花了一些时间研究部署技术。
对于我来说,要实现一个良好的设置还需要解决几个问题:
易于客户部署。 这非常重要,因为我们的网站将集成到其“实时” TYPO3安装中,该安装可服务大量网站,并且运行在不是由客户管理的服务器上,而是由另一个(集中的)组织进行服务呼叫和服务器更改 过程缓慢。
应该很容易更新。 如前所述,请求重新启动和更改服务器是一个缓慢的过程,因此,理想情况下,当节点安装收到使用forever
推送到实时安装中的更改时,应重新启动/更新。
部署方式
对于部署节点应用程序以使其保持运行状态,似乎普遍同意使用forever
。 我已经测试了forever
,并且在npm
(全局)下安装时似乎工作正常。 但是,这需要外部协助才能在实时环境中进行全局安装,因此我更希望从应用程序的node
目录中运行它,但是我无法创建一个可靠的包装器来执行此操作。
此外,forever
可以正常工作,但必须手动启动。 确保它在服务器启动时启动并保持运行的最佳方法是什么?
forever
脚本?forever
状态?快速开发/更新后重启
我们目前仍处于该项目的开发阶段,每当我对node.js应用程序进行更改时,我都会手动重新启动forever
或forever
。这行得通,但远非理想。有几个较小的npm
模块检查文件修改,并在检测到更改后重新启动node
,例如:
forever
结合使用)有人有经验吗?
更新:为什么不只使用群集?
群集模块通过重新加载机制提供了类似的功能,但不适用于Node 0.5+。 替换它的核心集群模块(节点0.6+)不具有所有这些功能,而仅提供集群。 这反过来在socket.io中不能很好地发挥作用。 至少并非没有使用Redis(这对我们来说是个问题,因为我们不能向客户强制提供其他先决条件服务)。
-
显然,在将项目交付给客户之前,我试图找到一种最稳定的解决方案,该解决方案将更新重新启动器与forever
结合在一起,我真的希望任何人都能产生出经过验证的技术组合。
我想将路由与server.js文件分开。
我正在Scotch.io上关注本教程[http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4]
如果所有行都在server.js文件上,则它可以正常工作。 但是我没有分开。 我该如何进行这项工作?
server.js
// set up ======================================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// configuration ===============================================================
app.use(bodyParser());
var port = process.env.PORT || 8000;
var mongoose = require('mongoose');
var database = require('./config/database');
mongoose.connect(database.url);
var Video = require('./app/models/video');
// routes =======================================================================
app.use('/api', require('./app/routes/routes').router);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("ready captain, on deck" + port);
module.exports = app;
还有app / routes / routes.js
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our rest video api!' });
});
router.route('/videos')
.post(function(req, res) {
var video = new Video();
video.title = req.body.title;
video.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Video criado!' });
});
})
.get(function(req, res) {
Video.find(function(err, videos) {
if (err)
res.send(err);
res.json(videos);
});
});
module.exports.router = router;
我有一个Ubuntu VM,无法连接到使用ssl(即https)的站点。 如果URL以http开头,它可以从Internet成功下载工件。
npm install将通过https下载依赖项。 反正有通过http下载吗?
如何使用Node.js从目录中删除所有文件而又不删除目录本身?
我想删除临时文件。 我对文件系统还不好。
我找到了此方法,它将删除文件和目录。 那样的话,像/path/to/directory/*
这样的东西将无法工作。
我真的不知道应该使用什么命令。 谢谢您的帮助。