以下代码获取文件内容,替换一些字符,然后输出结果:
测试.txt:
# Title
## Title 2
Paragraph
index.js:
#!/usr/bin/env node
require('babel/polyfill')
'use strict'
var fs = require('fs')
, filename = process.argv[2]
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME')
process.exit(1)
}
function massReplace(text, replacementArray) {
let results = text
for (let [regex, replacement] of replacementArray) {
results = results.replace(regex, replacement)
}
return results
}
function transformHeadings(text, orig) {
return massReplace(text,
[/^## (.*)/gm, '<h2>$1</h2>'],
[/^# (.*)/gm, '<h1>$1</h1>'] ]
)
}
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err
data = data.split(/\n\n/gm)
var tree = data.slice()
console.log(transformHeadings(data, tree))
})
我收到此错误:
alex@alex-K43U:~/node/m2n$ babel-node index4.js test.txt
/home/alex/node/m2n/index4.js:41
throw _iteratorError;
^
TypeError: undefined is not a function
at massReplace (/home/alex/node/m2n/index4.js:17:4)
at transformHeadings (/home/alex/node/m2n/index4.js:30:2)
at /home/alex/node/m2n/index4.js:39:3
at fs.js:336:14
at FSReqWrap.oncomplete (fs.js:99:15)
不知道问题是什么,也不知道 throw _iteratorError
意味着什么。
我正在使用Babel解析ES6代码。
可能是什么问题?
编辑:
这是编译后的函数。但我还是看不出问题所在:
function massReplace(text, replacementArray) {
var results = text;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = replacementArray[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = _slicedToArray(_step.value, 2);
var regex = _step$value[0];
var replacement = _step$value[1];
results = results.replace(regex, replacement);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"]) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return results;
}
我是一名优秀的程序员,十分优秀!