使用NodeJS在顶级文件上添加字符串 [英] Add string on top file with NodeJS

查看:205
本文介绍了使用NodeJS在顶级文件上添加字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的js文件顶部添加字符串.实际上,它就在最后:

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 ?

谢谢!

推荐答案

我认为在Node.js中没有内置的方法可以插入文件的开头.

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

但是您可以使用fsreadFileSyncwriteFile方法来解决此问题

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

它将在文件顶部append字符串

尝试一下

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;
});

方法#2

如果您依赖使用第三方模块,则可以使用 prepend 模块添加@robertklep建议的顶部字符串.

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);
});

这篇关于使用NodeJS在顶级文件上添加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆