为什么不写writeFile工作node.js

时间:2018-04-18 16:05:41

标签: node.js

为什么这次调用fs.writeFile不会有效?我在Linux Ubuntu上。调用是在这个gulp任务的最后,我尝试在文件上写一个我已经验证的字符串。 manifest [key]代码返回正确的文件名。它应该工作,除非我遗漏了一些愚蠢的东西。请帮忙! writefile调用未显示错误。但是文件没有写完。

gulp.task('injecttags', function() {
const manifest = jsonfile.readFileSync('./public/manifest/manifest.json');

const htmlkeys = [];
Object.keys(manifest).forEach((key) => {
    if (key.endsWith('.html')) {
        htmlkeys.push(key);
    }
});

htmlkeys.forEach((key) => {
    console.log("For key:", key);
    let file_content = fs.readFileSync('./public/html/'+manifest[key]).toString();
    console.log(file_content);
    let position = 0;
    while (((position = file_content.indexOf('<!-- INSERTSCRIPT=', position)) !== -1)) {
        const actualpositiontowriteto = file_content.indexOf('\n', position);
        const openquotepos = file_content.indexOf("'", position) + 1;
        const closequotepos = file_content.indexOf("'", openquotepos);
        const keystr = file_content.substring(openquotepos, closequotepos);
        const toinsert = `<script src="${manifest[keystr]}"></script>\n`;
        const beg = file_content.substr(0, position);
        const end = file_content.substr(actualpositiontowriteto);
        file_content = beg + toinsert + end;
    }
    position = 0;
    while (((position = file_content.indexOf('<!-- INSERTCSS=', position)) !== -1)) {
        const actualpositiontowriteto = file_content.indexOf('\n', position);
        const openquotepos = file_content.indexOf("'", position) + 1;
        const closequotepos = file_content.indexOf("'", openquotepos);
        const keystr = file_content.substring(openquotepos, closequotepos);
        const toinsert = `<link rel="stylesheet" href="${manifest[keystr]}">\n`;
        const beg = file_content.substr(0, position);
        const end = file_content.substr(actualpositiontowriteto);
        file_content = beg + toinsert + end;
    }

    fs.writeFile('./public/html/'+manifest[key], file_content, (err) => {
        if (err) return console.log('error writing file!', err);
        return console.log('successful file write');
    });
});
});

0 个答案:

没有答案