Stéphane R. Stéphane R. - 1 year ago 190
Node.js Question

Add string on top file with NodeJS

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 !

Answer Source

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


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;


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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download