node js array.push 'not' working
node js array.push 'not' working
我肯定犯了一个愚蠢的错误,但无法追踪它。有一个简单的脚本来读取以下形式的文件:
<option value="us">United States</option>
尝试创建表单的新文件:
{"value":"us","name":"United States"}
问题是jsonC.push(c)
不起作用,数组仍然为空。console.log(c)
确实打印json
表示形式,但下一行jsonC.push(c)
对数组没有任何影响jsonC
并且它仍然是空的。
这是代码:
var fs = require('fs');
var readline = require('readline');
var src = 'country.txt';
var dest = 'country.json';
var re = /.+["]('w{2})["][>]([a-zA-Z ]+)[<][/].+/;
var jsonC = [];
readline.createInterface({
input: fs.createReadStream(src), terminal: false
}).on('line', function(line) {
var match;
if ((match = re.exec(line)) !== null) {
var c = {};
c.value = match[1];
c.name = match[2];
console.log(c); // prints fine
jsonC.push(c); // not adding to the array
}
});
console.log(jsonC); // prints []
console.log(JSON.stringify(jsonC)); // prints []
这是一个在 Win 7
上运行的独立node.js v4.2.6
脚本。
原因是您在回调函数中向 jsonC 添加值。 readline.createInterface(...).on(function() {
是回调,不是同步的。所以你的程序只是调度那个函数,然后它console.log(jsonC)
并且 jsonC 仍然为空,因为回调尚未触发。
尝试在回调中输出值,或使用 promise 知道回调何时完成。
下面是一个使用 Promise 的工作示例:
function readFromFile() {
var fsRead = Promise.defer();
readline.createInterface({
input: fs.createReadStream(src), terminal: false
}).on('line', function(line) {
var match;
if ((match = re.exec(line)) !== null) {
var c = {};
c.value = match[1];
c.name = match[2];
jsonC.push(c);
fsRead.resolve();
}
});
return fsRead.promise();
}
readFromFile().then(function(result) {
console.log(jsonC);
})
相关文章:
- $rootScope not working
- jQuery document.ready not working
- Javascript getElementsByTagName not working?
- JQuery.val( ) not working
- Tomcat websocket is not working
- Javascript JSON.parse not working
- NodeJS Multer is not working
- Regex not working
- Ember run.debounce not working
- AngularJs 1 not working
- document.getElementById.style.backgroundImage not working
- Rxjs5, distinct() is not working
- createOscillator noteOn not working
- Javascript - .getHours() not working
- Javascript setTimeout not working | onkeydown
- MongoDB $pull not working
- Express router.use not working
- JSONP not working
- window.opener not working in chrome & IE
- Backbone + RequireJS: Collection.each() is not working