[英]Use variables among two exported functions
I am getting errors while using variable among two exported Node.js function在两个导出的 Node.js 函数中使用变量时出现错误
Variable name is buffer which is a Buffer.变量名是缓冲区,它是一个缓冲区。
Am i right in using variable buffer in js code ?我在 js 代码中使用可变缓冲区是否正确?
module.exports = {
var buffer ;
init: function(data)
{
buffer = data ;
},
test: function(word)
{
var readline = require('readline');
var stream = require('stream');
// string to buffer
var baseText = buffer;
var buf = new Buffer(baseText);
//buffer to stream
var bufferStream = new stream.PassThrough();
bufferStream.end(buf);
var readLines = readline.createInterface({
input: bufferStream,
});
var count = 0;
readLines.on('line', function (line)
{
if(line.toLowerCase().indexOf(word.toLowerCase()) != -1)
return true;
}
);
return false;
}
}
{...}
is an object literal. {...}
是一个对象字面量。 It can only contain property declarations ( name: value
).它只能包含属性声明( name: value
)。
var
is a statement; var
是一个语句; you can't put it in the middle of an object literal.你不能把它放在对象文字的中间。
You need to declare the variable separately.您需要单独声明变量。
You can't declare variables in Object literals.您不能在对象字面量中声明变量。 If you define outside module.exports
, then there won't any error.如果在module.exports
之外module.exports
,则不会有任何错误。
var buffer ;
function init(data) {
buffer = data ;
}
function test(word) {
var readline = require('readline');
var stream = require('stream');
// string to buffer
var baseText = buffer;
var buf = new Buffer(baseText);
//buffer to stream
var bufferStream = new stream.PassThrough();
bufferStream.end(buf);
var readLines = readline.createInterface({
input: bufferStream,
});
var count = 0;
readLines.on('line', function (line) {
if(line.toLowerCase().indexOf(word.toLowerCase()) != -1)
return true;
});
return false;
}
module.exports = {
init: init,
test: test
}
You can't declare a variable inside an object literal.您不能在对象字面量中声明变量。
Try something like this:尝试这样的事情:
var buffer;
module.exports = {
init: function(data) {}
// the rest of your code
}
This is similar to the revealing module pattern .这类似于揭示模块模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.