Hul*_*991 3 javascript arrays jquery node.js
我有一个数组
myarray = ["ram", "ram", "jan", "jan", "feb", "feb"]
是否可以创建一个以表格格式具有此值的 .txt 文件?
前端:
如果您的代码将在前端(浏览器)上,您可以使用以下内容:
var row_width = 40;
var content = "";
content += "Username" + new Array(row_width + 1).join(" ") + "Password\n";
content += "********" + new Array(row_width + 1).join(" ") + "********\n";
for (var i = 0; i < myarray.length; i += 2) {
content += myarray[i] + new Array(row_width - myarray[i].length + 9).join(" ");
content += myarray[i+1];
content += "\n";
}
// Build a data URI:
uri = "data:application/octet-stream," + encodeURIComponent(content);
// Click on the file to download
// You can also do this as a button that has the href pointing to the data URI
location.href = uri;
Run Code Online (Sandbox Code Playgroud)
这是一个工作前端示例的链接:Fiddle
将该文件命名为 something.txt。
后端:
如果要在后端使用 Node.js 生成并保存此文件,则需要使用以下内容:
循环遍历数组并创建上述“内容”字符串后,按如下方式保存文件:
var fs = require('fs');
fs.writeFile("/path_to_file/table.txt", content, function (err){
if (err) {
console.log(err);
} else {
console.log("File saved");
}
});
Run Code Online (Sandbox Code Playgroud)
我还没有尝试过该代码,但请随时告诉我它是否适合您。我希望这就是你所需要的。
请注意,某些过时/糟糕的浏览器可能不支持前端代码
| 归档时间: |
|
| 查看次数: |
9526 次 |
| 最近记录: |