很多时候,我们遇到过一些实例,我们有一个特定的文本文件,我们希望使用我们的Javascript代码。不是在服务器上单独托管该文本文件,而是将该文件的每一行写入Javascript字符串并将它们连接起来以在运行时创建字符串。
一个典型的例子是着色器代码。 Three.js代码有许多着色器代码文件的例子,它们作为Javascript代码中的字符串嵌入。
有没有可以做到的标准/成熟实用程序?即将文本文件作为输入并生成.js文件作为输出。
或者我应该写一个自己的小脚本? (如果有人可以提供精确的awk
/ sed
命令,那也很有趣。
答案 0 :(得分:1)
15行python应该可以解决这个问题
#Matthew Downey, 2/18/2014
#jsConvert.py
import sys
if len(sys.argv) != 4:
print "Usage:", sys.argv[0], "<inputfile.txt> <outputFile.js> <varName>"
exit()
f = open(sys.argv[1], "r")
lines = f.readlines()
f.close()
jsCode = '"' + lines[0].replace("\n", "\\n") + '"'
for line in lines[1:]:
line = line.replace("\n", "\\n")
jsCode = jsCode + ' + ' + '"' + line + '"'
jsCode = "var " + sys.argv[3] + " = " + jsCode + ";\n"
f = open(sys.argv[2], "a")
f.write(jsCode)
f.close()
如果我跑
python jsConvert.py test.txt outPut.js questionText
这将包含一个文本文件 test.txt ,其中包含您问题的文字文本,并生成一个如下所示的文件outPut.js:
var questionText = "Many times we come across instances where we have a certain text file that we want to ship with our Javascript code. Instead of hosting that text file separately on server, it makes sense to write each line of that file into Javascript strings and concatenate them to create a string at runtime.\n" + "\n" + "A typical example is shader code. Three.js code has many example of shader code files embedded as strings inside Javascript code.\n" + "\n" + "Is there any standard/mature utility that can do it? i.e. take the text file as input and generate .js file as output.\n" + "\n" + "Or should I just write a small script of my own? (If someone can give a pithy awk/sed command, that would be interesting too)";
如果你继续将文本文件输入到同一个输出文件中,它会附加,因此它只会生成包含所需文本的多个变量。
希望这有帮助!
答案 1 :(得分:0)
#!/bin/bash
#
# Usage: <scriptname> <input-text-file> <output-js-file>
{
echo "var file_contents ="
sed 's/"/\\"/g; s/^/"/; s/$/" +/' "$1"
echo '"";'
} > "$2"