node.js将相对路径字符串添加到数组复制斜杠

时间:2011-12-17 21:04:11

标签: javascript json node.js

我有以下简单的场景:

  1. 我解析manifest.json(一个JSON文件)
  2. 我将一些路径添加到此JSON对象的数组字段
  3. 我将对象字符串化回JSON并写回文件
  4. 问题出现在介于两者之间:当我向数组添加相对路径然后输出数组时,我的输出中会出现双反斜杠。

    这是代码的一部分:

    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' ]
    

    这怎么可能? “总数组输出”中的第一个条目不等于直接记录最后一个条目的输出。

    May 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”,     “description”:“”,     “content_scripts”:[         {             “火柴”: [                 “http://www.example.com”             ]             “js”:[                 “程序\ boot.js”             ]             “css”:[                 “prime.css”             ]             “run_at”:“document_start”         }     ] }

    最后,我在Windows 7上运行它。

1 个答案:

答案 0 :(得分:2)

您在格式化字符串中使用%a,这没有任何意义,因此console.log会检查数组。可能%a只是一个错字,你真的是%s