Javascript node.js将相对路径字符串添加到数组会复制斜杠
我有以下简单的场景:Javascript node.js将相对路径字符串添加到数组会复制斜杠,javascript,json,node.js,Javascript,Json,Node.js,我有以下简单的场景: 我解析manifest.json(一个json文件) 我向这个JSON对象的数组字段添加了一些路径 我将对象字符串化回JSON并写回文件 在这两者之间的某个地方出现了一个问题:当我向数组添加一个相对路径,然后输出数组时,我在输出中得到了两个反斜杠 这是代码的一部分: var entry = manifest['content_scripts'][0]['js'] = []; routines.forEach(function(routine) { v
var entry = manifest['content_scripts'][0]['js'] = [];
routines.forEach(function(routine) {
var rel = path.relative(sourcePath, routine);
console.log('rel %s', rel);
entry.push(rel);
console.log('added rel %s', entry[entry.length-1]);
console.log('total array %a', entry);
});
这将返回:
rel routines\boot.js
added rel routines\boot.js
total array %a [ 'routines\\boot.js' ]
这怎么可能?“总数组输出”中的第一项不等于直接记录最后一项的输出
JSON.stringify可能会在这里引起问题吗
额外:对于那些感兴趣的人,这是整个构建脚本:
var path = require('path'),
fs = require('fs'),
findit = require('findit'),
sourcePath = path.resolve('./src'),
manifestPath = path.join(sourcePath, 'manifest.json'),
routinesDir = path.join(sourcePath, 'routines');
//find routines
var routines = findit.sync(routinesDir);
if (!Array.isArray(routines) || routines.length === 0) throw new Error('no routines found');
//get file
fs.readFile(manifestPath, 'utf8', function(err, data) {
if (err) throw err;
//get manifest
var manifest = JSON.parse(data);
//flush and reset js entry
var entry = manifest['content_scripts'][0]['js'] = [];
routines.forEach(function(routine) {
var rel = path.relative(sourcePath, routine);
console.log('rel %s', rel);
entry.push(rel);
console.log('added rel %s', entry[entry.length-1]);
console.log('total array %a', entry);
});
//get string back
var manifestStr = JSON.stringify(manifest, null, 4);
console.log('new manifest: ' + manifestStr);
//update file
fs.writeFile(manifestPath, manifestStr, 'utf8', function(err) {
if (err) throw err;
//done
console.log('build done');
});
});
对于manifest.json:
{
“名称”:“名称”,
“版本”:“0.0.1”,
“说明”:“,
“内容脚本”:[
{
“匹配项”:[
"http://www.example.com"
],
“js”:[
“例程\boot.js”
],
“css”:[
“prime.css”
],
“运行时间”:“文档开始”
}
]
}
最后,我将在Windows 7上运行此操作。您在格式化字符串中使用了
%a
,它没有任何意义,因此console.log
将检查数组。可能%a
只是一个输入错误,您真正的意思是%s
目的是检查数组,因为问题就是在这个时候出现的。当串接时,会出现相同的问题。我应该如何记录数组?我的意思是,当你给console.log
除字符串以外的任何东西时,它将“检查”对象,而不仅仅是使用toString
将其字符串化。这意味着您的数组将被“检查”,数组中的字符串也将被检查。现在,当您检查一个字符串时,Node将其格式化,与您将其格式化为字符串文本的方式相同。由于反斜杠需要转义,所以节点就是这样格式化的。尝试将总数组%a
更改为总数组%s
,您就会明白我的意思。我想说的是,%a
完全错误。您写它时出错,您的意思是%s
。%s不是字符串吗?我没有试图输出一个字符串,我试图输出一个带有字符串的数组。无论如何,使用JSON.stringify时问题仍然存在(这可能也是console.log内部使用的)。这是正确的行为<代码>“foo\\bar”是字符串的正确JSON表示形式,该字符串由“foo”后跟反斜杠再后跟“bar”组成。