Add string on top file with NodeJS

烂漫一生 提交于 2020-01-15 10:13:46

问题


I would like add string on the top of my js file. Actuly, it's on the end :

var file = './public/js/app.bundleES6.js',
    string = '// My string';

    fs.appendFileSync(file, string);

Do you have idea for add my string on the first line ?

Thank you !


回答1:


I think there is no built-in way to insert at the beginning of the file in Node.js.

But you can use readFileSync and writeFile methods of fs to resolve this issue

It will append string at top of the file

Try this

Method#1

var fs = require('fs');
var data = fs.readFileSync('./example.js').toString().split("\n");
data.splice(0, 0, "Append the string whatever you want at top" );
var text = data.join("\n");

fs.writeFile('./example.js', text, function (err) {
  if (err) return err;
});

Method#2

If you are relying on to use third party module then you can use prepend module to add the string at the top as suggested by @robertklep.

var prepend = require('prepend');

prepend(FileName, 'String to be appended', function(error) {
    if (error)
        console.error(error.message);
});


来源:https://stackoverflow.com/questions/39635259/add-string-on-top-file-with-nodejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!